Move a Sprite at a certain speed in a specific angular direction
You can use some basic trigonometric functions to convert this angle and speed to component x and y velocities. First, you need to make sure the angle is in radians. If the angle is in degrees, convert it by using the following formula:
radians = degrees * Math.PI / 180;
If you ever need to convert the opposite way, use:
degrees = radians * 180 / Math.PI;
Once you have the angle in radians, use the Math.sin and
Math.cos functions, along with the speed, to find the x and y
velocities, using the following formulas:
vx = Math.cos(angle) * speed;
vy = Math.sin(angle) * speed;
Here is an example using 135 degrees and a speed of 4 pixels per frame:
package {
import flash.display.Sprite;
import flash.events.Event;
import flash.events.TimerEvent;
import flash.utils.Timer;
public class AngularVelocity extends Sprite {
private var _sprite:Sprite;
private var _angle:Number = 135;
private var _speed:Number = 4;
private var _timer:Timer;
public function AngularVelocity ( ) {
_sprite = new Sprite( );
_sprite.graphics.beginFill(0x0000ff, 100);
_sprite.graphics.drawCircle(0, 0, 25);
_sprite.graphics.endFill( );
_sprite.x = 200;
_sprite.y = 100;
addChild(_sprite);
_timer = new Timer(30);
_timer.addEventListener("timer", onTimer);
_timer.start( );
}
public function onTimer(event:TimerEvent):void {
var radians:Number = _angle * Math.PI / 180;
var vx:Number = Math.cos(radians) * _speed;
var vy:Number = Math.sin(radians) * _speed;
_sprite.x += vx;
_sprite.y += vy;
}
}
}