Recipe 11.2. Moving
an Object in a Specific Direction
Problem
You want
to move an object at a certain speed in a specific angular
direction.
Solution
Convert the speed and angle to x and
y velocities and add these to the object's x and
y position on each frame or animation interval.
Discussion
Recipe
11.1 explains how you can move something at specific velocities
on the x and y-axes, but what if you just know the
angle and speed you want an object to move? For example, you want
the object to move at an angle of 135 degrees, with a speed of 4
pixels per frame.
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;
Then you can simply move the object as outlined
in Recipe
11.1. 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;
}
}
}
Of course, in such a simple example, it wouldn't
make sense to recalculate the x and y velocities on
each interval, as they never change. Instead, just calculate it one
time, save the result, and use it on each frame. In many cases,
however, the speed and direction will be constantly changing, and
therefore need to be computed new for each frame.
See Also
Recipe
11.1
|