Wednesday 4 January 2012

Varying the rotation speed

One objection to rotating using complex numbers instead of angles is that it works best with a fixed rotation speed. This is correct: if the speed needs to vary from frame to frame then the 'delta' needs to be recalculated each frame, and it may be easier to just use the angle to calculate the rotation each time.

But as long as the speed is mostly fixed complex numbers work well. If for example the rotation speed changes in steps, but between these is constant, then the 'delta' needs only be recalculated at these steps.
The code is as follows, for both the fixed speed rotation and changing speed (where the constraint is the motion takes a second or 30 frames).

function AimGun():void {
    // use the angle to set complex number for step
    if (bVarSpeed) {
        // fixed time step, varying speed
        // need to recalculated the step
        var fStep:Number = (fAngle2 - fAngle1) / 30;
        rStep = Math.cos(fStep);
        iStep = Math.sin(fStep);
        iTime1 = 31;
    } else {
        // fixed speed        
        // it is either the same as initially calculated or
        // it's conjugate, depending on the direction of rotation
        if (fAngle2 > fAngle1) {
            rStep = rDelta;
            iStep = iDelta;
        } else {
            rStep = rDelta;
            iStep = -iDelta;
        }

        // get the time from the angles
        iTime1 = Math.abs(fAngle2 - fAngle1) / stepAngle;
    }
    // rotate gun to current direction
    RotateGun(r1, i1);
}

rStep and iStep are the complex number multiplied each frame to incrementally rotate the gun, using the function described yesterday.

I've updated my latest ballistics app with this and embedded it below. Click outside the coverage range (above the red line) to toggle the behaviours. I've also added some comments to the source code.


No comments:

Post a Comment