Skip to content

Instantly share code, notes, and snippets.

@TyOverby
Created September 30, 2011 06:32
Show Gist options
  • Save TyOverby/1252875 to your computer and use it in GitHub Desktop.
Save TyOverby/1252875 to your computer and use it in GitHub Desktop.
Rotates a point around another point
public class EntryPoint {
public static class Point{
public final double x;
public final double y;
public Point(double x,double y){
this.x = x;
this.y = y;
}
public String toString(){
return "("+this.x+","+this.y+")";
}
}
public static void main(String... args) {
Point curPos = new Point(-10,-10);
Point rotPos = new Point(0,0);
System.out.println(getRotatedPoint(curPos,rotPos,0).toString());
}
public static Point getRotatedPoint(Point curPos,Point rotPos,double r){
//get the current angle from the rotation point to the current point
double currentRot=getCurRot(curPos,rotPos);
//get the current radius of the circle drawn around the rotPos that intersects the curpos
double magnitude=getMagnitude(curPos,rotPos);
//MATH STUFFS
double x = Math.cos(r+currentRot)*magnitude + rotPos.x;
double y = Math.sin(r+currentRot)*magnitude + rotPos.y;
return new Point(x,y);
}
/**
* Gets the current angle from the rotational point to the current point
* @param curPos The current position
* @param rotPos The position of the point that you want to rotate around
* @return
*/
public static double getCurRot(Point curPos,Point rotPos){
double diff_y = (curPos.y-rotPos.y);
double diff_x = (curPos.x-rotPos.x);
double diff = diff_y/diff_x;
if(diff==Double.NaN){
return 0;
}
else{
double toReturn = Math.atan(diff);
if(diff_y<0 && diff_x<0){
System.out.println(diff);
//if both are negative, add pi/2
toReturn += Math.PI;
System.out.println("trigger 1");
}
else if(diff_x<0 && !(diff_y<0)){
//if x is less than 0 and y isn't
toReturn = -toReturn;
toReturn+=Math.PI/2;
System.out.println("trigger 2");
}
return toReturn;
}
}
public static double getMagnitude(Point a, Point b){
double x_dist = Math.abs(a.x-b.x);
double y_dist = Math.abs(a.y-b.y);
return Math.sqrt(Math.pow(x_dist, 2)+Math.pow(y_dist,2));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment