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);
}