[AS3]as3中键盘操作控制实例源代码
通过键盘控制物体的移动,改变物体的线速度即可以改变它的运动状态。通过监听舞台的MouseEvent.MOUSE_DOWN和MouseEvent.MOUSE_UP事件来移动物体。当mouseDown时,设置一个Boolean值记下按下的方向键,在Event.ENTER_FRAME事件中根据设置的Boolean值来移动物体
通过键盘控制物体的移动,改变物体的线速度即可以改变它的运动状态。通过监听舞台的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; bbbb = bb.m_next )
- {
- if (bb.m_userData is DisplayObject)
- {
- bbbb.m_userData.x = bb.GetPosition().x * _physcale;
- bbbb.m_userData.y = bb.GetPosition().y * _physcale;
- bbbb.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());
- }
- }
- }
热门文章推荐
- [HLS]做自己的m3u8点播系统使用HTTP Live Streaming(HLS技术)
- [FMS]FMS流媒体服务器配置与使用相关的介绍
- [AS3]什么是M3U8,与HTML5的区别是什么
- AS2.0 让flash自适应全屏,并且不自动缩放
- [AS3]as3.0的sound类常用技巧整理
- [AS3]as3与ByteArray详解、ByteArray介绍、ByteArray用法
- 关于RTMP,RTMPT,RTMPS,RTMPE,RTMPTE协议的介绍
- [JS]分享浏览器弹出窗口不被拦截JS示例
请稍候...