Results 1 to 5 of 5
Thread: [SOLVED] Simple Trig Thing
- 05-16-2009, 05:57 AM #1
Senior Member
- Join Date
- Jan 2009
- Location
- NJ, USA
- Posts
- 200
- Rep Power
- 5
[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.
- 05-16-2009, 06:28 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.add(test); f.setSize(300,300); f.setLocation(200,200); f.setVisible(true); double theta = test.getAngle(); System.out.printf("theta = %.1f%n", Math.toDegrees(theta)); } }
- 05-16-2009, 06:34 AM #3
Senior Member
- Join Date
- Jan 2009
- Location
- NJ, USA
- Posts
- 200
- Rep Power
- 5
Thanks a ton!
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.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; }
- 05-16-2009, 06:40 AM #4
Java measures angles positive clockwise from 3 o'clock.
The order of p1/p2 is important.
- 05-16-2009, 06:45 AM #5
Senior Member
- Join Date
- Jan 2009
- Location
- NJ, USA
- Posts
- 200
- Rep Power
- 5
Similar Threads
-
What did i do wrong on thing method?
By PureAwesomeness in forum New To JavaReplies: 9Last Post: 03-08-2009, 08:37 AM -
Need help with a simple Java thing involving array of objects
By Jeremy8 in forum New To JavaReplies: 5Last Post: 02-25-2009, 07:14 PM -
Help with a very simple method for a very simple beginner.
By cakeman in forum New To JavaReplies: 2Last Post: 05-04-2008, 05:27 PM -
Using the Math Trig Methods
By Java Tip in forum java.langReplies: 0Last Post: 04-16-2008, 10:54 PM -
PLz i really need help on this final thing
By jason27131 in forum New To JavaReplies: 2Last Post: 08-03-2007, 02:31 AM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks