- Home /
Trigger on reaching target rotation only working the first few times.
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.
Answer by duck · Mar 08, 2010 at 07:58 PM
You're probably running into problems to do with imprecision when comparing floating point values.
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
}
Thank you. Your Quaternion.Angle code was exactly what I wanted. It solved the problem, but I had to remove the f after the 0.1. I upped the number to 1 and it made it slightly more responsive, as if it was taking a few frames to complete the last degree.
Ah, yes the 'f' is C# syntax required when writing a floating point value. If your writing in JS, you don't need it.
Your answer
Follow this Question
Related Questions
Can't click gameobject when over another trigger? 1 Answer
Object rotate to target in 2D? Not working properly. 0 Answers
Quaterion is rotating my character improperly? 1 Answer
how to make a simple full rotational quaternion for cameras 3 Answers
How to initiated floors to fall like dominos once the game starts 2 Answers