Angle between two objects in 2D space

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;
	
	}
2 Likes

You could use this instead:

Note that these are vectors, so basically what you want to do, I’m guessing, in your case is:

Vector3.Angle(Vector3.up, obj2.transform.position - obj1.transform.position);

or something similar.

The “angle between two objects” is essentially a nonsensical statement even if the objects are in a plane. You probably implicitly think of it in relation to one of the coordinate system base vectors.

1 Like

Ok, let me make it a bit more proper: The angle I would need to rotate my character, on the Y axis, from zero in order to be facing a specific point on the same plane.

I do think that’s what I need, though. I knew there had to be an easier way. :slight_smile:

Thanks!

Thank you so much for this! I had a terrible headache trying to figure this out. I added this to display the way I wanted before returning the variable

ang -= 90;
ang = -ang;
// barf it back to the calling function
return (float)ang;

It’s giving a value that is 90 degrees of and it makes more sense to me to get a positive value rather than a negative.

1 Like