Matching Tranforms returns false though they appear to match

I have the following code:

if (transform.rotation == aimRotation )
            {
                aiming = false;
            }

where the first transform.rotation = “(0.0, -0.1, 0.0, 1.0)”
and the aimRotation = “(0.0, -0.1, 0.0, 1.0)”
yet the statement above never makes it to the aiming = false line. Now the true values for x, y, z do not match as in the -0.1 may actually be -0.0589878 but I am comparing the rotation value not the actual x,y,z. Any ideas why unity sees them as not matching?

Well first off whenever dealing with floats, you should never rely on == to work. I’d pick some small value and compare the difference:

if ( Mathf.Abs(floatOne-floatTwo) < .01)
      // Do stuff when they are equal

Secondly transform.rotation is a Quaternion , which is a strange beast all together. It has four member main members w,x,y,z that are coeffeicients to a matrix that describes the objects rotation. Who knows how == is overloaded or how it operates on Quaternions.

Rotations do have a way to get at the x,y,z angles of a rotation though:

transform.rotation.eulerAngles

Does your code necessarily care about the rotation in all 3 dimensions? If you just care about the rotation around the Y-Axis (3D character turning around in the world) you could use :

if (transform.rotation.eulerAngles.y == aimrotation.eulerAngles.y)

OR

if (Mathf.Abs(transform.rotation.eulerAngles.y-aimrotation.eulerAngles) < toleranceValue)

Change the .y to .z if working in 2D

1 Like

Thanks. I was doing the == becasue the actual value for the rotation is “(0.0, -0.1, 0.0, 1.0)” in the debug inspector, but you could be right about any overloads that may get more detailed. I found (just to see my scene work) that if I ToString the “(0.0, -0.1, 0.0, 1.0)” value, i get the correct matches, but it is just for testing, too much overhead for that funtion when you have a couple hundred entities all aiming.

I am in 3D on a terrain, so it is possible that an entitiy might point “downward” towards another if it is on a mountain or cliff. I will give you example a run this evening to see if things smooth out.

It’s important to note that values in the console will be rounded for readability.

There’s also the Mathf.Approximately function to check if two floats are very close.

2 Likes

If you’re comparing rotations you could also check if the angle between them is near 0 or check the dot product to see if they face in the same direction

1 Like

Thanks all, will give all of these a look and see what works for my game.