How do i tell java its closer to go 350 -> 355 -> 360 -> 05 degrees instead of all the way around

121 views Asked by At

I'm creating a racing game, in which I run into some problems while creating the AI. What I need to do is get the AI from a X,Y position to a "checkpoint" with another X,Y position. The AI driving track will be created by placing different invisible checkpoints around the map that is will go to.

I can get the direction to the checkpoint by calculating the difference in X,Y from me to it and then use tan(Deg) = Y/X, witch gives me the direction I have to go from my current position.

distanceToMoveX = checkpoint1X - this.getX();
distanceToMoveY = checkpoint1Y - this.getY();
newDirection = ((double)distanceToMoveY / distanceToMoveX) * 100;

So now I have the direction in which I have to go from my current position, and I also have a direction in which I'm currently moving. What I want to do now is get my AI to realize its closer to turn right if my current direction is 350 and I want to go to 10. As it is right now I can only get it to turn right or left all the time.

3

There are 3 answers

0
Rodrigo Quesada On BEST ANSWER

This is what you need for choosing the direction (this is an example with hardcoded values):

private int correctedDirectionCalculation(int calculation){
   return calculation >= 0 ? calculation : calculation + 360;
}

public void chooseDirection() {
    int targetDirection = 5;
    int currentDirection = 360;

    int goingRightDistance = correctedDirectionCalculation(targetDirection - currentDirection);
    int goingLeftDistance = correctedDirectionCalculation(currentDirection - targetDirection);

    System.out.println(goingLeftDistance < goingRightDistance ? "Go Left!" : "Go Right!");
}

As for the inverted values on the Y axis when rendering, I guess you just need to invert the Y value to fix it (multiply by -1).

0
Void On

You can use degrees outside the range of (0;360), so you can f.e. go from 360 to 365 and it works as expected. If you want later to, say, compare two angles, just say angle % 360

0
Cimbali On

Well I guess somewhere you compute the difference between the actual angle and the next one, something like turn = newDirection - actualDirection.

Doing 10 - 350 = -340 tells you AI it needs to turn -340°.

However, (10 - 350 + 360) % 360 = 20 tells your AI it needs to turn +20°. Adding the 360 is to make sure your angle is positive, so the modulo will work as expected (because -340 % 360 = -340).

What you really want, is never turn more than 180°. Thus, add another 180 before reducing between 0 and 360, and then remove them, that will shift your result in [-180,180] while staying module 360° (thus the same angle) :

turn = (newDirection - actualDirection + 540) % 360 - 180

Then you breakup this turn however you want if you don't want it to do in one go, for example 5 degrees at a time like you seem to be already doing.