I have an object smoothly rotating using Quaternion.Slerp towards a variable called 'target', which is set by a Quaternion.LookRotation.
I have set an if statement to trigger an action when I reach the target rotation
if (transform.rotation == rotate)
This works for the first several movements, but then only works intermittently. Does anyone have any ideas on what this might be?
I thought there might be a rounding error, meaning it never reaches the actual value, so tried accepting a value that was near, but Quaternion values will not accept a plus or minus, so I cannot do if (transform.rotation - rotate > 3 && transform.rotation - rotate < -3) for example.
You could use Quaternion.Angle to check whether the difference between the current angle and the target angle is below a given threshold. For example:
if (Quaternion.Angle(transform.rotation, rotate) < 0.1f) {
// we're within 0.1 degrees of the target... close enough!
}
Alternatively, if you're actually linearly Slerping towards a target (that is, feeding in a start and end rotation, as opposed to feeding in the current and end rotation, then you would be able to tell whether the Slerp has reached the end angle when the value for the 3rd argument of Slerp is greater than or equal to 1.
Eg:
if (rotationFactor <= 1) {
transform.rotation = Quaternion.Slerp(startRot, endRot, rotationFactor)
} else {
// we have reached the end rotation
}