Thrusting in different directions

Image by dognamedseven from Pixabay

When you press the control key, the player’s ship will accelerate in whatever direction (0-23) it is facing. To make this possible, I pre-populated a couple of float arrays with values x and y for thrust in any of the 24 directions.

This function populate the two arrays. These are declared as

float thrustx[24];
float thrusty[24];

void InitThrustAngles() {
    const float pi = 3.14159265f;
    const float degreeToRad = pi / 180.0f;
    float degree = 0.0f;
    for (int i = 0; i<24; i++) {
        float radianValue = degree * degreeToRad;
        thrustx[i] = (float)sin(radianValue);
        thrusty[i] = (float)-cos(radianValue);
        degree += 15;

It uses trigonometry to calculate the horizontal and vertical amounts for any of the angles 0,15,30..345 degrees. As sin and cos functions work in radians rather than degrees, the variable radianValue is calculated from the degree angle by multiplying by the value degreesToRad. If you remember your school trigonometry, one radian = 180/pi degrees. So the code divides by this value (or multiplies by its inverse in this case).

Then when you press the control key, it just adds the appropriate thrustx and thrusty value to the vx and vy variables. Simple and fast.


(Visited 42 times, 1 visits today)