物体的运动(一)

为物体的运动做一个总结:

在FlashDevelop中建立一个FlashIDE工程,新建一个Fla文件到工程目录,在Fla文件中新建一个库元件Circle(类名,一个圆形Sprite),接下来新建两个类,一个是主类Main.as,一个是Circle.as。

package  
{
	import flash.display.Sprite;
	
	/**
	 * ...
	 * @author ywxgod--http://www.cnblogs.com/ywxgod/
	 */
	public class Circle extends Sprite
	{
		public var vx:Number = 0;
		public var vy:Number = 0;
		public var ax:Number = 0;
		public var ay:Number = 0;
		public var mass:int = 3;
		public var friction:Number = 0.96;
		
		public function Circle() 
		{
			
		}
		
	}

}

Circle类中定义了一些基本的属性,有x,y方向的速度和加速度,摩擦力,质量等,为了简单,我全部定义public类型。

package  
{
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.KeyboardEvent;
	import flash.events.MouseEvent;
	
	/**
	 * ...
	 * @author ywxgod--http://www.cnblogs.com/ywxgod/
	 */
	public class MoreFoundation extends Sprite
	{
		private var _circle:Circle;
		
		public function MoreFoundation() 
		{
			if (stage) init();
			else addEventListener(Event.ADDED_TO_STAGE, init);
		}
		
		private function init(e:Event=null):void
		{
			appInit();
		}
		
		private function appInit():void 
		{
			_circle = new Circle();
			addChild(_circle);
			_circle.x = stage.stageWidth / 2 - _circle.width / 2;
			_circle.y = stage.stageHeight / 2 - _circle.height / 2;
			
			stage.addEventListener(KeyboardEvent.KEY_DOWN, keyboardDownEventHandle);
			stage.addEventListener(KeyboardEvent.KEY_UP, keyboardUpEventHandle);
			addEventListener(Event.ENTER_FRAME, onFrame);
		}
		
		private function keyboardDownEventHandle(e:KeyboardEvent):void 
		{
			switch(e.keyCode)
			{
				case 38://up
					_circle.ay = -1;
					break;
				case 40://down
					_circle.ay = 1;
					break;
				case 37://left
					_circle.ax = -1;
					break;
				case 39://right
					_circle.ax = 1;
					break;
			}
		}
		
		private function keyboardUpEventHandle(e:KeyboardEvent):void 
		{
			_circle.ax = 0;
			_circle.ay = 0;
		}
		
		private function onFrame(e:Event):void 
		{
			_circle.vy += _circle.ay;
			_circle.vx += _circle.ax;
			_circle.vx *= _circle.friction;
			_circle.vy *= _circle.friction;
			_circle.x += _circle.vx;
			_circle.y += _circle.vy;
			
			vxTi.text = _circle.vx.toFixed(2);
			vyTi.text = _circle.vy.toFixed(2);
		}
		
	}

}

Main类中,监听舞台的键盘事件,主类的EnterFrame事件,在键盘事件中根据不同的按键,设置不同的方向的加速度,在EnterFrame事件中应用到物体上。

将加速度加到速度上,再将速度加到x,y坐标上,如果有摩擦力,则速度要乘以一个摩擦系数再加到x,y坐标上。

vxTi,vyTi分别是舞台上两个TextInput组件,用来记录物体的x,y方向的速度。

posted @ 2010-04-10 11:02  ywxgod  阅读(382)  评论(0编辑  收藏  举报