11.1.移动物体

问题
在sprite中有个图形,我想让它动起来
解决办法
先决定x或y轴(或两者)的速率,然后在每一帧中通过速率改变物体的位置
讨论
速率和速度不是同一个概念,速率还包含方向因素,比如说:"10 米每小时" 是速度,但是"10米每小时正北方向"是速率。在x或y轴上肯定是考虑方向的,一个正的速率代表x轴的右边,负的为左边。

第一个例子定义了x速率:_vx,设置为3,而且例子使用了enterFrame事件做动画,在每一帧上对象向右移动3像素:
+展开
-ActionScript
package {
import flash.display.Sprite;
import flash.events.Event;
public class Velocity extends Sprite {
private var _sprite:Sprite;
private var _vx:Number = 3;
public function Velocity( ) {
_sprite = new Sprite( );
_sprite.graphics.beginFill(0x0000ff, 100);
_sprite.graphics.drawCircle(0, 0, 25);
_sprite.graphics.endFill( );
_sprite.x = 50;
_sprite.y = 100;
addChild(_sprite);
addEventListener(Event.ENTER_FRAME, onEnterFrame);
}
public function onEnterFrame(event:Event):void {
_sprite.x += _vx;
}
}
}

如果设置_vx为-3,你会发现物体在向反方向移动。现在我们再添加y速率:_vy,给它个值,修改下onEnterFrame方法,如下:
+展开
-ActionScript
public function onEnterFrame(event:Event):void {
_sprite.x += _vx;
_sprite.y += _vy;
}

如果你不喜欢基于帧做动画(上面的例子),还可以使用定时器函数:
+展开
-ActionScript
package {
import flash.display.Sprite;
import flash.events.Event;
import flash.events.TimerEvent;
import flash.utils.Timer;
public class Velocity extends Sprite {
private var _sprite:Sprite;
private var _vx:Number = 3;
private var _vy:Number = 2;
private var _timer:Timer;
public function Velocity( ) {
_sprite = new Sprite( );
_sprite.graphics.beginFill(0x0000ff, 100);
_sprite.graphics.drawCircle(0, 0, 25);
_sprite.graphics.endFill( );
_sprite.x = 50;
_sprite.y = 100;
addChild(_sprite);
_timer = new Timer(30);
_timer.addEventListener("timer", onTimer);
_timer.start( );
}
public function onTimer(event:TimerEvent):void {
_sprite.x += _vx;
_sprite.y += _vy;
}
}
}

加支付宝好友偷能量挖...


评论(0)网络
阅读(74)喜欢(0)flash/flex/fcs/AIR