Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

Awesomeness

macrumors member
Original poster
Feb 12, 2009
73
0
Ok, I need to find the angle 'tween two points on a 2D plane. This would be the angle in comparison to vertical. For example,

Code:
This is 0 degrees

||
||
||
||
||
()

This is 45 degrees

||
||   //
||  //
|| //
||//
()

This is 90


||
||
||
||
||___________
()___________

Yeah, I'm working with Java. Could some one post the equation, the pseudo code, or Java code?

Thanks.
 

lee1210

macrumors 68040
Jan 10, 2005
3,182
3
Dallas, TX
I really hope this isn't homework. I made an inner class myPoint to demonstrate, i assume you already have a point class in place that you could use/extend:

Code:
public class testtrig {
  public static void main(java.lang.String args[]) {
    testtrig x = new testtrig();
    myPoint p1 = x.new myPoint(1000.,1.);
    myPoint p2 = x.new myPoint(0.,0.5);
    System.out.println("The result for p1 and p2 is: " + p1.getAngleInDegreesWith(p2));

    System.out.println("The result from origin of p1: " + p1.getAngleInDegreesWithOrigin());
  }
  public class myPoint {
    double xCoor; //We'll let them default to protected, so we can act on other myPoints in methods
    double yCoor; 
    myPoint(double x,double y) {
      this.xCoor = x;
      this.yCoor = y;
    }

    public double getX() { return xCoor;}
    public double getY() { return yCoor;}

    public double getSlopeWith(myPoint p) {
      return (java.lang.Math.abs(p.xCoor - xCoor) / java.lang.Math.abs(p.yCoor - yCoor));
    }

    public double getAngleInDegreesWith(myPoint p) {
      return java.lang.Math.toDegrees(java.lang.Math.atan(this.getSlopeWith(p)));
    }

    public double getSlopeWithOrigin() {
      return xCoor/yCoor;
    }
    
    public double getAngleInDegreesWithOrigin() {
      return java.lang.Math.toDegrees(java.lang.Math.atan(this.getSlopeWithOrigin()));
    }
  }
}

It isn't the most beautiful or best documented, but it should get you the angle in degrees. I didn't do any I/O, the main class is just to demonstrate the use of some of the functions. You would want to add error checking that the slope wasn't infinity/undefined, etc.

-Lee

Edit: I was guessing at which angle you wanted, exactly... i figured that if you were working with the origin and some point with positive x and y value the angle you'd want would be the one between the x-axis and the line segment between the two points. If that isn't what you want, it should be easy to adjust... it's all a little trig. I didn't want to calculate the line segment length for use, that's why i went with tangent. Someone might need to check my logic for negative x and y values. It's saturday.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.