Smooth rotation problem
I can't figure out how to create a smooth rotation, when patroling object reaches turning point. At the moment it just snaps to that direction.
private void Update()
{
transform.position = Vector3.MoveTowards(transform.position, waypoints[startIndex].position, Time.deltaTime * speed);
if(transform.position == waypoints[startIndex].position)
{
ChangeDestination();
}
ChangeRotation();
}
void ChangeDestination()
{
if (reverse)
{
DetermineDirection();
}
startIndex = nextIndex;
nextIndex = (startIndex + direction) % waypoints.Length;
if(nextIndex < 0)
{
nextIndex += waypoints.Length;
}
}
void DetermineDirection()
{
if(nextIndex == 0 || nextIndex == waypoints.Length - 1)
{
direction *= -1;
}
transform.up = waypoints[nextIndex].position - transform.position;
Vector2 dir = (waypoints[nextIndex].position - transform.position).normalized;
angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg - 90;
newRot = Quaternion.AngleAxis(angle, Vector3.forward);
}
void ChangeRotation()
{
transform.rotation = Quaternion.Slerp(transform.rotation, newRot, 0.1f);
}
Comment
StartCoroutine( LinearRotationRoutine(transform.rotation,newRot) , 0.1f );
// preview: https://i.imgur.com/ZDkj3cT.gif
IEnumerator LinearRotationRoutine ( Quaternion src , Quaternion dst , float duration )
{
float timeStart = Time.time;
float timeEnd = timeStart + duration;
while( Time.time < timeEnd )
{
yield return null;
float animationTime = Mathf.Clamp01( ( Time.time - timeStart ) / duration );
transform.rotation = Quaternion.Slerp( src , dst , animationTime );
}
}
// preview: https://i.imgur.com/mhRzyWl.gif
IEnumerator ElasticRotationRoutine ( Quaternion src , Quaternion dst , float duration )
{
float timeStart = Time.time;
float timeEnd = timeStart + duration;
while( Time.time < timeEnd )
{
yield return null;
float animationTime = Mathf.Clamp01( ( Time.time - timeStart ) / duration );
animationTime = easeOutElastic( animationTime );
transform.rotation = Quaternion.SlerpUnclamped( src , dst , animationTime );
}
float easeOutElastic ( float t )
{
const float c4 = (2f*Mathf.PI)/3f;
return t==0 ? 0 : t==1 ? 1 : Mathf.Pow(2f,-10f*t)*Mathf.Sin((t*10f-0.75f)*c4)+1f;
}
}
Answer by Nicolas_Granese · May 28 at 03:57 PM
Hello, @AarnasS75 Try using Quaternion.RotateTowards.
Quaternion lookRotation = Quaternion.LookRotation(waypoint[ ].position - transform.position);
transform.rotation = Quaternion.RotateTowards(transform.rotation, lookRotation, duration);
Your answer
Follow this Question
Related Questions
Unity 2D rotation not smooth? 0 Answers
Rotation before 0 and after 360 0 Answers
Vector3.RotateTowards doesn't work with angles of 180 degrees 0 Answers