This is both a question and an answer.
So I’ve been trying to figure out how to get the angle between two objects that are assumed to be on the same plane. I have a character that the player has given a destination to walk to. I want that character to turn towards that destination, but I don’t want him to lean back as he walks if it’s uphill (that’s not realistic – one is more likely to lean forward).
I got a workable solution, but it seems a bit clunky. I also tried a function juggling quaternions a bit, but it came out rather comical. Does anyone know a more elegant way of doing this? I’m sort of thinking built-in functions here.
If it’s helpful to anyone else, here’s the function:
public float GetAngle(float X1, float Y1, float X2, float Y2) {
// take care of special cases - if the angle
// is along any axis, it will return NaN,
// or Not A Number. This is a Very Bad Thing(tm).
if (Y2 == Y1) {
return (X1 > X2) ? 180 : 0;
}
if (X2 == X1) {
return (Y2 > Y1) ? 90 : 270;
}
float tangent = (X2 - X1) / (Y2 - Y1);
// convert from radians to degrees
double ang = (float) Mathf.Atan(tangent) * 57.2958;
// the arctangent function is non-deterministic,
// which means that there are two possible answers
// for any given input. We decide which one here.
if (Y2-Y1 < 0) ang -= 180;
// NOTE that this does NOT need to be normalised. Arctangent
// always returns an angle that is within the 0-360 range.
// barf it back to the calling function
return (float) ang;
}