这是一个物体被抛动的例子,原例子来自于《Flash ActionScrpt3 动画教程》一书,我在此做了小小修改,加入了球体自身的转动效果。
先用FlashDevelop建立一个FlashIDE工程,建立一个主Fla文件Main.fla,在Main.fla中创建一个继承自Sprite类型的圆形,链接类名为Ball,记下球体的半径,此例中我画的球半径为25。新建一个Ball类,设置其vx,vy属性用来保存球的速度,具体代码:
Ball.as
package { import flash.display.Sprite; /** * ... * @author ywxgod--http://www.cnblogs.com/ywxgod/ */ public class Ball extends Sprite { public var vx:Number = 0; public var vy:Number = 0; public function Ball() { } } }
Main.as
package { import flash.display.Sprite; import flash.events.Event; import flash.events.MouseEvent; /** * ... * @author ywxgod--http://www.cnblogs.com/ywxgod/ */ public class Main extends Sprite { private var _ball:Ball; private var _bounce:Number = -0.8; private var _gravity:Number = 0.5; private var _oldx:Number; private var _oldy:Number; public function Main() { if (stage) init(); else addEventListener(Event.ADDED_TO_STAGE, init); } private function init(e:Event = null):void { _ball = new Ball(); addChild(_ball); _ball.vx = Math.random() * 10 - 5; _ball.vy = -10; _ball.x = stage.stageWidth / 2; _ball.y = stage.stageHeight / 2; _ball.addEventListener(MouseEvent.MOUSE_DOWN, onDown); addEventListener(Event.ENTER_FRAME, onFrame); } private function onDown(e:MouseEvent):void { _oldx = _ball.x; _oldy = _ball.y; stage.addEventListener(MouseEvent.MOUSE_UP, onUp); _ball.startDrag(); addEventListener(Event.ENTER_FRAME, trackVelocity); removeEventListener(Event.ENTER_FRAME, onFrame); } private function trackVelocity(e:Event):void { _ball.vx = _ball.x - _oldx; _ball.vy = _ball.y - _oldy; _oldx = _ball.x; _oldy = _ball.y; } private function onUp(e:MouseEvent):void { stage.removeEventListener(MouseEvent.MOUSE_UP, onUp); removeEventListener(Event.ENTER_FRAME, trackVelocity); addEventListener(Event.ENTER_FRAME, onFrame); stopDrag(); } private function onFrame(e:Event):void { _ball.rotation += _ball.vx; _ball.vy += _gravity; _ball.x += _ball.vx; _ball.y += _ball.vy; setBounds(); } private function setBounds():void { var left:Number = 0; var right:Number = stage.stageWidth; var top:Number = 0; var bottom:Number = stage.stageHeight; if (_ball.x+25>right) { _ball.x = right - 25; _ball.vx *= _bounce; } else if (_ball.x-25<left) { _ball.x = left + 25; _ball.vx *= _bounce; } if (_ball.y+25>bottom) { _ball.y = bottom - 25; _ball.vy *= _bounce; } else if (_ball.y-25<top) { _ball.y = top + 25; _ball.vy *= _bounce; } } } }
在鼠标点击球体时,记下球当前的位置,在函数trackVelocity执行中(此时正拖动着球体,鼠标未释放):
每帧将球当前的位置,减去前一位置的x,y方向的距离赋予球的x,y方向的速度。
释放鼠标时,球的x,y方向的速度即为:释放鼠标前最后一帧中球前后连个位置的差值,也就是看在最后一帧中移动球的距离多少,距离越大,释放鼠标时球的速度越大。
在setBounds()中,直接用的是球的半径25,没有用_ball.width/2或者_ball.height/2。这样做的作用在前一篇已经说明。