Friday, 30 December 2011

Angle-free rotation

In my last post I showed how to aim a gun at a target above or below the gun to fire a ballistic missile, i.e. one moving under gravity. The mathematics was entirely angle and trigonometry free, but I noted that the angle can be calculated, in case it's need to e.g. rotate a gun turret. But it's not actually needed for that: it's possible to generate the rotation matrix to line up an object with a direction, without using angles.

The code is as follows

function RotateGun(gun:Bitmap, x:Number, y:Number):void {
    gun.transform.matrix = new Matrix(x, y, -y, x,
        fGunX + y * fSize / 2, fGunY - x * fSize / 2);

The rotation is calculated from 'x' and 'y', the components of a normalised direction vector.  These are passed to the first four parameters of the matrix, as shown, and used to offset its position it so it rotates around the midpoint of its shortest length.

I've updated my ballistics app (again embedded below) with this code rotating two guns, one for each ball. Note that the above works for an object normally aligned along the 'x' axis and so horizontally, which is how I made the gun. The normalised direction vector is simply the velocity divided by the speed.

No comments:

Post a Comment