Skip to content

Instantly share code, notes, and snippets.

@estebanpadilla
Created August 31, 2013 22:44
Show Gist options
  • Save estebanpadilla/6401118 to your computer and use it in GitHub Desktop.
Save estebanpadilla/6401118 to your computer and use it in GitHub Desktop.
Method for Unity to get angle using a start and end points. Code can be improve.
private float GetAngleFromPosition(float x1, float y1, float x2, float y2){
float o = 0;
float a = 0;
bool doingA = false;
bool doingB = false;
bool doingC = false;
bool doingD = false;
if(x1 >= x2 && y1 <= y2){//set for A
o = x1 - x2;
a = y2 - y1;
doingA = true;
}else if(x1 >= x2 && y1 >= y2) { // set for B
a = x1 - x2;
o = y1 - y2;
doingB = true;
}else if(x1 <= x2 && y1 >= y2){//set for C
o = x2 - x1;
a = y1 - y2;
doingC = true;
}else if( x1 <= x2 && y1 <= y2){//set for D
o = y2 - y1;
a = x2 -x1;
doingD = true;
}
// print("o: " + o);
// print("a: " + a);
float angle = Mathf.Rad2Deg*Mathf.Atan(o / a);
angle = Mathf.Ceil(angle);
if(doingB){ angle += 90; }
else if (doingC) { angle += 180; }
else if (doingD) { angle += 270; }
return angle;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment