Question

This problem is hard to explain, so I'll use an image to aid me:

error image

I'm trying to find an angle between the middle of the tank, to the mouse. The orange dot denotes the mouse position, the red line separates the two instances, and the green/lime line shows the tank's turret angle. I've been looking through stack overflow multiple times, and yet to no avail have I found a solution to my problem. I've even googled. In both, I have found many groups of code to 'find an angle'. I'm sure that these work, so I doubt my problem lies in the hands of bad code. I'm GUESSING that the error is found within the MouseMotionListener.

The two points I'm using to create the psuedo-line (NOT the green or red lines) to are the tank's middle point new Point(Tank.getX() + 16, Tank.getY() + 16) (the tanks size is 32x32) and the mouse point (set when there is a new mouse moved event).

Details about my program:

  • A frame is created and has a MouseMotionListener attached to it.
  • A JPanel is created and added to the frame.
  • Everything is drawn onto the JPanel.

In short, my getAngle() code is wrong, my MouseMotionListener is wrong, or I'm giving the wrong parameters. What is the problem?...

EDIT: As asked for in the comments here is my code and the output:

Code:

public static float getAngle(Point source, Point destination) {
  System.out.println(source + "\n" + destination);
  double xDiff = source.x - destination.x;
  double yDiff = source.y - destination.y;
  System.out.println((float) Math.toDegrees(Math.atan2(yDiff, xDiff)));
  return (float) Math.toDegrees(Math.atan2(yDiff, xDiff));
}

Output:

java.awt.Point[x=116,y=116] // Source point
java.awt.Point[x=134,y=123] // Destination point
-158.7495
Was it helpful?

Solution

Well, after plenty of Googling, I found that there really was no error. All the code was correct, all.. pretty much everything was correct. The only thing that was wrong was that it was off by 90 degrees. This thought had crossed my mind multiple times, but every time I looked at the dot and the line, it just didn't seem right... The fixed code is below:

public static float getAngle(Point source, Point destination) {
  System.out.println(source + "\n" + destination);
  double xDiff = source.x - destination.x;
  double yDiff = source.y - destination.y;
  System.out.println((float) Math.toDegrees(Math.atan2(yDiff, xDiff)));
  return (float) Math.toDegrees(Math.atan2(yDiff, xDiff)) + 90.0F;
}

For some reason, I feel like I've just dropped a couple IQ points for overlooking this multiple time.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top