Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unity rotation difference and direction

I would like to know the rotation difference between two objects on one Axis, like for example on Y axis.

I tried using Quaternion.Angle but it calculate whole rotation, not on one axis

using

angle=transform.rotation.eulerAngles.y-target.transform.rotation.eulerAngles.y;

works, however this does not tell me the target's direction compared to me, how many angles to the left or to the right?

edit: no it doesn't work, it only works if both transforms' x and z rotation axis is 0.

If, for example I put both start rotation at (349.8176,113.8314,254.5617) ,then I rotate the target 3 degrees to its right, it became (352.7103,113.0266,254.684), which will return an Y angle difference of 0.8 instead of 3

like image 596
Alvin Wiltan Avatar asked Aug 06 '26 12:08

Alvin Wiltan


1 Answers

You could simply use the scalar product between the forward vectors to determine if they both face in the same direction or look at (or away from) each other:

float dot = Vector3.Dot( transform.forward, target.transform.forward );
bool sameDirection = dot >= 0;

You could even use vector math to compute the angle without to roll out the huge quaternion canon:

// align forward vectors to the XZ plane / Y axis first
Vector3 sourceForward = transform.forward;
Vector3.OrthoNormalize( Vector3.up, ref sourceForward );
Vector3 targetForward = target.transform.forward;
Vector3.OrthoNormalize( Vector3.up, ref targetForward );

// get the angle between both transforms arount the Y axis
float dot = Vector3.Dot( sourceForward, targetForward );
float angleRad = Mathf.Acos( dot );
float angleDeg = Mathf.Rad2Deg( angleRad );

// see if the angle is clockwise or counter-clockwise
Vector3 up = Vector3.Cross( sourceForward, targetForward );
angleDeg = up.y < 0 ? -angleDeg : +angleDeg;

Disclaimer: This all is purely theoretical because I have no possibility to test this with Unity 3D at the moment.

like image 167
swalex Avatar answered Aug 08 '26 00:08

swalex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!