Search code examples
javarotationtrigonometryslick2d

Rotate player to face objective java slick


So I am currently working on learning slick. I was doing fine until I ran into a problem. I have been trying to find a answer for a good hour and could not. So I decided to post it on here.

My Problem: I have player on a 800 X 800 Grid. I am trying to make the player move to a certain point on the grid in a straight line. Now I can make him move on the X then turn and move on the Y, But I want to make him get there as fast as possible. So I figured if I could make a right triangle from the following points (Player pos, Target Pos, and the X,Y intercept see my image bellow).

My code:
Adj = (int) (TargetX-x); // Get The size of the Adjacent leg.
Opp =   (int) (TargetY-y); // Get the size of the Opposite leg.
OppAdj = Opp/Adj;          //Inverse tan is Opposite/Adjacent
TargetAngle =  Math.abs(Math.atan(Opp/Adj)*100);  //Keep the angle positive, and use inverse tan to get the missing angle.

Now what I thought this would do, is solve for the missing angle so I could rotate the player by that amount so the player can move in a straight line and hit the objective.

What this ends up doing though is is giving me a target angle of 73 degrees and a the Variable OppAdj ends up being 1.0.

What is wrong with my code?

Any help is appreciated!

Thanks, Kyle


Solution

  • OppAdj = Opp/Adj;
    

    That is the problem. You should do this:

    OppAdj = (double)(Opp)/Adj;
    

    That way it will give you a double for accuracy. By the way:

    TargetAngle =  Math.abs(Math.atan(Opp/Adj)*100);
    

    Should be:

    TargetAngle =  Math.abs(Math.atan(OppAdj)*100);