- Home /
How to get the positive or negative angle between objects?
I need to decide if I want something to swivel left or right towards my target. Currently, angle only seems to return positive values. I need to find out, if two objects are level, if I need to add angles to the y rotation of my object, or subtract angles in order for it to eventually face towards my target.
Is there a straightforward function in Unity I've overlooked?
Answer by duck · Apr 23, 2010 at 11:28 AM
You can use Mathf.Atan2 to compute the angle between 2D vectors. This only works for 2d rotations though, however often that's all you need even in a 3d game. Eg:
var localTarget = transform.InverseTransformPoint(target.position);
var targetAngle = Mathf.Atan2(localTarget.x, localTarget.z);
However, the "angle" will be in radians, not degrees, so you most probably want to convert it to degrees before using it, like this:
var targetAngle = Mathf.Atan2(localTarget.x, localTarget.z) * Mathf.Rad2Deg;
This should give you the target angle in the range -180 to 180 degrees.
Duck, you're a genius! I spend several hours trying to acomplish angle calculations to rotate enemy towrads waypoint! in 2 damn fantastic lines! 1000 times THAN$$anonymous$$S!
After DAYS of searching, I found the solution! Thank you, Ben $$anonymous$$t! Finally somebody answers this question without telling the person that their question "doesn't make sense."
InverseTransformPoint would be something like this in OpenT$$anonymous$$?
public Vector3 InverseTransformPoint(Vector3 position)
{
$$anonymous$$atrix4 mat = $$anonymous$$atrix4.Transpose(Generate$$anonymous$$atrix());
$$anonymous$$atrix4 matT = $$anonymous$$atrix4.Translation(position) * mat;
return new Vector3(matT.$$anonymous$$14, matT.$$anonymous$$24, matT.$$anonymous$$34);
}
Answer by spinaljack · Apr 23, 2010 at 10:33 AM
You can test to see if the angle returned it more than 180 and then reverse the rotation your self (-360).
Something like:
function getAngle(){ // angle code if (Angle > 180) Angle -= 360; return Angle; }
// do your rotation
This the common-sense solution. Some people try too hard.
Answer by _MGB_ · May 06, 2010 at 07:39 AM
A nice trick for 3d: the cross product of two vectors is a vector quantity with a magnitude equal to the product of the magnitudes of the two vectors times the sine of the angle between them.
So for two normalised vectors:
angle_diff = asin(cross(v1, v2).len())
The resulting vector can be used as an axis for rotation between the two input vectors.
whhhaatt? what does cross product do? why is it useful? How can this be applied to posative / negative angles?
Your answer
Follow this Question
Related Questions
Rotating without gimbal lock 1 Answer
using mouseorbit script and Rotate Around with specific angle 1 Answer
Rotate from angle to angle 1 Answer
Rotate 90 over time on mouseDown 2 Answers
Rotate parent so child is facing a specific rotation 1 Answer