cangleradians

How to detect a rotated radian?


I'm doing LunarLander in C. My ship rotates between PI/2 and -PI/2. And rotation per step is PI/ 20. I need a way to detect when my ship rotated 1 radian. So, when 1 radian rotates, the fuel decreases me by 1 unit.

What I thought is to first pass my angle to degrees and then see if the angle is greater than 57, because 1 radian is 57 degrees. But I couldn't write it in my program because the idea is incomplete. While this is just something I thought, I think the solution comes from that side, compare with those 57 degree

while(1)
//code
    case SDLK_RIGHT:
        angle += SHIP_ROTATION_PER_STEP;
        if(angle > (PI/2)){
            angle = (PI/2);
            break;
        }
        break;
    case SDLK_LEFT:
        angle -= SHIP_ROTATION_PER_STEP;
        if(angle < -(PI/2)){
            angle = -(PI/2);
            break;
        }
        break;  
//code
//during the while

I need an idea to compare if all that moved my ship was 1 radian. If the sum of the rotations per step were greater than 1 radian. But I can't think how


Solution

  • Keep an accumulator total_angle. Whenever the ship rotates in either direction, add the absolute value of the rotation. Assuming your rotations are in the floating-point double type that means this:

    total_angle += fabs(angle); /* angle is the increment in angle */
    

    Let's assume that angle and total_angle are simply measuring radians directly and not some scaled integer version or whatever. In that case, whenever total_angle reaches or exceeds 1.0, we subtract a unit of fuel. At the same time, we subtract 1.0 from the accumulator:

    if (total_angle >= 1.0) {
        fuel--;
        total_angle -= 1.0;
    }
    

    We're assuming that a single rotation is no greater than one radian, otherwise we'd have to make this a while loop.