- Home /
Quaternion.RotateTowards is inconsistent
I use Quaternion.RotateTowards
the same way as in documentation to rotate a game object smoothly (I want it to face a target). It mostly works as expected, but once it reaches a small enough angle (though much larger than max degrees delta), it jumps to target rotation instantly. On attached image you can also see how angle changes are not consistent at all, but it's not noticeable in gameplay. (I think these changes can be explained by targeted game object rotating?) The jump, however, is noticeable. Any idea what is happening and how to fix this?
Console :
Code (fragment of a method called from Update) :
if (Mathf.Abs(Vector3.Angle(hit.point - lr.transform.position, lr.transform.forward)) < lasersRotSpeed * Time.deltaTime)
{
converged++;
lr.transform.LookAt(hit.point);
}
else
{
Debug.Log(lr.name + " before " + Vector3.Angle(hit.point - lr.transform.position, lr.transform.forward) + " " + (Mathf.Abs(Vector3.Angle(hit.point - lr.transform.position, lr.transform.forward)) < lasersRotSpeed * Time.deltaTime));
lr.transform.rotation = Quaternion.RotateTowards(lr.transform.rotation, Quaternion.LookRotation(hit.point - lr.transform.position, lr.transform.up), lasersRotSpeed * Time.deltaTime);
// lr.transform.rotation = Quaternion.LookRotation(Vector3.RotateTowards(lr.transform.forward, (hit.point - lr.transform.position).normalized, Mathf.Deg2Rad * lasersRotSpeed * Time.deltaTime, 0)); // Does nothing, probably due to float precision delta is 0
Debug.Log(lr.name + " after " + Vector3.Angle(hit.point - lr.transform.position, lr.transform.forward) + " " + (Mathf.Abs(Vector3.Angle(hit.point - lr.transform.position, lr.transform.forward)) < lasersRotSpeed * Time.deltaTime));
}
I would recommend starting with better code formatting:
float deltaTime = Time.deltaTime;
Transform lrTransform = lr.transform;
Vector3 dir = hit.point - lrTransform.position;
Quaternion targetRotation = Quaternion.LookRotation( dir );
float calcAngle () => Quaternion.Angle( lrTransform.rotation , targetRotation );
float calcAngleAbs () => Mathf.Abs( calcAngle() );
if( calcAngleAbs() < lasersRotSpeed * deltaTime )
{
converged++;
lrTransform.LookAt( hit.point );
}
else
{
Debug.Log( $"{lr.name} before {calcAngle()} {(calcAngleAbs()<lasersRotSpeed*deltaTime)}" );
lrTransform.rotation = Quaternion.RotateTowards(
from: lrTransform.rotation ,
to: targetRotation ,
maxDegreesDelta: lasersRotSpeed * deltaTime
);
Debug.Log( $"{lr.name} after {calcAngle()} {(calcAngleAbs()<lasersRotSpeed*deltaTime)}" );
}
Nobody wants to read a wall of hieroglyphs
Your answer
Follow this Question
Related Questions
Calculate rotation angle for two side of cube ( like dice ) from Quaternion.identity 0 Answers
Rotate object towards another object without using the local Y axis 0 Answers
Check if Rotation Angle is reached? 1 Answer
Rotate floor plane in-game via C# script 1 Answer
Rotation according to gravity 1 Answer