# Thread: [SOLVED] Simple Trig Thing

1. Senior Member
Join Date
Jan 2009
Location
CA, USA
Posts
271
Rep Power
12

## [SOLVED] Simple Trig Thing

I'm trying to make a method that finds the angle (in degrees) of the line between two points. It's been a while since I've taken trig, so I looked up some stuff... but honestly, I don't think I got it right. This is what I tried to do, but it isn't working.
Java Code:
```		public void mouseReleased(MouseEvent event)
{
bullets.add(new Item(X, Y, 5, 5, 50, getAngle(X, Y, event.getX(), event.getY())));
}

...

public int getAngle(int x1, int y1, int x2, int y2)
{
int a = (int)Math.toDegrees(Math.atan(Math.toRadians((y2-y1)/(x2-x1))));

return a;
}```
Last edited by AndrewM16921; 05-16-2009 at 06:29 AM.

2. Java Code:
```import java.awt.*;
import java.awt.geom.Line2D;
import javax.swing.*;

public class Test extends JPanel {
Point p1 = new Point(50, 50);
Point p2 = new Point(250, 175);

protected void paintComponent(Graphics g) {
super.paintComponent(g);
((Graphics2D)g).draw(new Line2D.Double(p1, p2));
}

private double getAngle() {
double dy = p2.y - p1.y;
double dx = p2.x - p1.x;
return Math.atan2(dy, dx);
}

public static void main(String[] args) {
Test test = new Test();
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(300,300);
f.setLocation(200,200);
f.setVisible(true);
double theta = test.getAngle();
System.out.printf("theta = %.1f%n",
Math.toDegrees(theta));
}
}```

3. Senior Member
Join Date
Jan 2009
Location
CA, USA
Posts
271
Rep Power
12
Thanks a ton!

Java Code:
```	public int getAngle(int x1, int y1, int x2, int y2)
{
int a = (int)Math.toDegrees(Math.atan2((y2-y1), (x2-x1)));

return -a + 90;
}```
The only problem I have is that I have to negate a and add 90 for it to be the right angle, but I don't understand why.

4. Java measures angles positive clockwise from 3 o'clock.
The order of p1/p2 is important.

5. Senior Member
Join Date
Jan 2009
Location
CA, USA
Posts
271
Rep Power
12

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•