Ludicrous Software

Flash Lite 1.1: Rotation Toward a Point

Rotating a movie clip so that it point toward a specific point is a handy little technique. If you’re using Flash Lite 2 and up, it’s pretty easy; this code will do it for you:

// 'point' is what we want to rotate toward
pointX = 50;
pointY = 50;
// 'rotater' is the clip that we want to rotate,
// so that it's pointing toward 'point'
rotaterX = 100;
rotaterY = 100;
// get the X and Y distances between the two objects
dX = pointX - rotaterX;
dY = pointY - rotaterY;
// find the angle between the two objects
radians = Math.atan2(dY, dX);
// convert from radians to degrees
angle = radians * 180 / Math.PI;
// apply the angle
radar._rotation = angle;

What makes this such a simple technique is the use of Math.atan2(), which does all the heavy lifting.

The Math class is available in Flash Lite 1.1, which is based on Flash 4 ActionScript. But, as the help docs in Flash 8 (although not Flash CS3) say, “In Flash Player 4, the methods and properties of the Math class are emulated using approximations and might not be as accurate as the non-emulated math functions that Flash Player 5 supports.” Math.atan2 is one area where the Math class is inaccurate. The result of this is that rotation toward a point only works as expected when the _x value of the point is larger than the _x value of rotating object.

The work-around for this is some extra code that checks the exact position of the point object, and adjusts the value of the angle accordingly. This sample file shows how all of this works. If you publish this as a Flash Lite 1.1 file, you’ll see that the arrow doesn’t point in the right direction when the ball is to the left of the arrow. If you publish the file as a Flash Lite 2 or higher file, the code works as expected. To get it to work in Flash Lite 1.1, you need to uncomment the conditional code in the second frame.