- Home /
How do I check a rotation relative to another object's rotation?
Hi! I need to check an object's rotation relative to another object's rotation. Just like the image, I need to know when the yellow ball has rotated outside the brown boundaries set by the blue ball. I have a problem since the blue ball also rotates and I don't know how to check it. To add some context, the blue ball are my character's legs which rotate as given by the arrow keys (up, down, left, right, up-left, down-right, etc), and the yellow ball is the upper body which rotates relative to the mouse, but I can't have the legs facing south and the upper body facing north, so I need to check rotations to be able to change the leg's animation.
I don't know the exact answer but I think vecto3.angel can work for you. Please check http://docs.unity3d.com/ScriptReference/Vector3.Angle.html
Answer by Mikilo · Aug 31, 2015 at 09:16 AM
Hello!
You might use this code to calcul some angles.
public static class Utility
{
public static float RelativeAngle(Vector3 fwd, Vector3 targetDir, Vector3 upDir)
{
var angle = Vector3.Angle(fwd, targetDir);
if (Utility.AngleDirection(fwd, targetDir, upDir) == -1)
return -angle;
else
return angle;
}
public static float RelativeAngle(Vector2 fwd, Vector2 targetDir, Vector3 upDir)
{
var angle = Vector2.Angle(fwd, targetDir);
if (Utility.AngleDirection(fwd, targetDir, upDir) == -1)
return -angle;
else
return angle;
}
public static float AngleDirection(Vector3 fwd, Vector3 targetDir, Vector3 up)
{
Vector3 perp = Vector3.Cross(fwd, targetDir);
float dir = Vector3.Dot(perp, up);
if (dir > 0F)
return 1F;
else if (dir < 0F)
return -1F;
else
return 0F;
}
public static float AngleDirection(Vector2 fwd, Vector2 targetDir, Vector3 up)
{
Vector3 perp = Vector3.Cross(new Vector3(fwd.x, 0f, fwd.y),
new Vector3(targetDir.x, 0f, targetDir.y));
float dir = Vector3.Dot(perp, up);
if (dir > 0F)
return 1F;
else if (dir < 0F)
return -1F;
else
return 0F;
}
}
In your case, your might need this particular code:
float angle = Utility.RelativeAngle(FORWARD_OF_YOUR_LEGS, FORWARDS_OF_YOUR_HEAD, Vector3.up);
I'm sorry, but I'm trying to implement your code to see if it works and I have no idea what "NGUtility" is and I can't find it anywhere. Forgive me for my noobiness... really.
Holy shit, sorry I replaced the class name only.. I edit it for you.
No problem, thank you very much, I was really stuck with this :D
You are welcome my friend, good luck.
As far as I remember, RelativeAngle will give you an angle from your front, -180 to 0 if it is in left side, and 0 to 180 if in the right side.