简单的键盘控制
通过键盘控制物体的移动,改变物体的线速度即可以改变它的运动状态。通过监听舞台的MouseEvent.MOUSE_DOWN和MouseEvent.MOUSE_UP事件来移动物体。当mouseDown时,设置一个Boolean值记下按下的方向键,在Event.ENTER_FRAME事件中根据设置的Boolean值来移动物体,具体如下:
1.添加监听
addEventListener(Event.ENTER_FRAME, onFrame);
stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDownHandle);
stage.addEventListener(KeyboardEvent.KEY_UP, onKeyUpHandle);
2.创建物体,创建时设置一个名称,因为现实对象为MovieClip,所以可以动态增加其属性。
createCircle(this, 30, 300, 20, 0, false, new Circle());
private function createCircle(container:DisplayObjectContainer,xpos:int,ypos:int,radius:int,rotation:Number,isStatic:Boolean,obj:MovieClip):void
{
var shapeDef:b2CircleDef = new b2CircleDef();
isStatic?shapeDef.density = 0:shapeDef.density = 5;
shapeDef.restitution = 0.1;
shapeDef.friction = 0.4;
shapeDef.radius = radius / _physcale;
var bodyDef:b2BodyDef = new b2BodyDef();
bodyDef.angle = rotation;
bodyDef.position.Set(xpos / _physcale, ypos / _physcale);
bodyDef.userData = obj;
var body:b2Body = _world.CreateBody(bodyDef);
body.CreateShape(shapeDef);
body.SetMassFromShapes();
obj.scaleX = radius*2 / obj.width;
obj.scaleY = radius * 2 / obj.height;
obj.name = "hero";
obj.body = body;
container.addChild(obj);
}
3.处理事件
private function onKeyDownHandle(e:KeyboardEvent):void
{
setBoolean(e.keyCode, true);
}
private function onKeyUpHandle(e:KeyboardEvent):void
{
setBoolean(e.keyCode,false);
}
private function setBoolean(keyCode:int, flag:Boolean ):void
{
switch(keyCode)
{
case 37:
isLeft = flag;
break;
case 38:
isUp = flag;
break;
case 39:
isRight = flag;
break;
}
}
private function onFrame(e:Event):void
{
moveBody();
_world.Step(_timeStep, _iteration);
for (var bb:b2Body = _world.m_bodyList; bb; bb = bb.m_next )
{
if (bb.m_userData is DisplayObject)
{
bb.m_userData.x = bb.GetPosition().x * _physcale;
bb.m_userData.y = bb.GetPosition().y * _physcale;
bb.m_userData.rotation = bb.GetAngle() * 180 / Math.PI;
}
}
}
private function moveBody():void
{
var child:MovieClip = this.getChildByName("hero") as MovieClip;
var body:b2Body = child.body as b2Body;
if (isLeft)
{
body.WakeUp();
body.m_linearVelocity.x -= 0.5;
}
if (isRight)
{
body.WakeUp();
body.m_linearVelocity.x += 0.5;
}
if (isUp)
{
if (body.m_linearVelocity.y > -1)
{
body.WakeUp();
body.ApplyImpulse(new b2Vec2(0, -30), body.GetWorldCenter());
}
}
}
E-mail:给我发邮件
出处:http://ywxgod.cnblogs.com
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。