Search code examples
mathgeometrytrigonometryradiansatan2

radian atan2 is showing opposite values then what they need to be


double shootx = vx + dx / t0;
double shooty = vy + dy / t0;
double radians = atan2((double)-shooty, shootx);
deg_to_aim = (int)((radians * 360) / (2 * 3.141592653589793238462));
myprintf("(A) radians = %f deg to aim = %d\n", radians, deg_to_aim);

radians 3.14 = 180 should be 0
radians 0    =   0 should be 180 

radians -1.584827 =  -90 should be 90
radians -1579912  =   90 should be -90

how do I make the values show up properly for all sides. At the moment if I spin around the dot it will show a out wards motion like behind actual point when it should have the point always pointing at the dot. Also it goes from 179 to -179 never hitting the 180.

Full code looks like this

        /* Relative player position */
        float const dx = (MyShip.XCoordinate + 18) - (Enemy.XCoordinate + 18);
        float const dy = (MyShip.YCoordinate + 18) - (Enemy.YCoordinate + 18);
        /* Relative player velocity */
        float const vx = MyShip.XSpeed - Enemy.XSpeed;
        float const vy = MyShip.YSpeed - Enemy.YSpeed;

        float const a = vx * vx + vy * vy - bulletSpeed * bulletSpeed;
        float const b = 2.f * (vx * dx + vy * dy);
        float const c = dx * dx + dy * dy;
        float const discriminant = b * b - 4.f * a * c;

        int deg_to_aim = 0;

        if (discriminant >= 0) {
            float t0 = (float)(-b + sqrt(discriminant)) / (2 * a);
            float t1 = (float)(-b - sqrt(discriminant)) / (2 * a);

            if (t0 < 0.f || (t1 < t0 && t1 >= 0.f))
                t0 = t1;
            if (t0 >= 0.f)
            {
                // Aim at
                double shootx = vx + dx / t0;
                double shooty = vy + dy / t0;
                double radians = atan2((double)-shooty, shootx);
                deg_to_aim = (int)((radians * 360) / (2 * 3.141592653589793238462));
                myprintf("(A) radians = %f deg to aim = %d\n", radians, deg_to_aim);
            }
        }
        else {
            myprintf("Error found!!!!!!! no solution\n");
        }

Solution

  • Fixed it just Flip the MyShip Enemy values around.

    Instead of MyShip - Enemy
    you do Enemy - MyShip