I'm trying to move and rotate a gameobject inside a coroutine to smoothly reach a target position. To do this I tried using Mathf.SmoothDamp()
to calculate a factor, which I use in a lerping function. This is my method:
private IEnumerator ReachTarget()
{
_speed = 0f;
var lerpFactor = 0f;
var startingPosition = transform.position;
var startingRotation = transform.rotation;
while (lerpFactor < 0.99f)
{
lerpFactor = Mathf.SmoothDamp(lerpFactor, 1f, ref _speed, 1f);
transform.position = Vector3.Lerp(startingPosition, _targetTransform.position, lerpFactor);
transform.rotation = Quaternion.Lerp(startingRotation, _targetTransform.rotation, lerpFactor);
yield return null;
}
transform.position = _targetTransform.position;
transform.rotation = _targetTransform.rotation;
}
Based on the documentation for Mathf.SmoothDamp() it should change my lerpFactor
from 0
to 1
in one second, which in turn should move and rotate my object to to it's target position in one second. This however simply doesn't happen and it takes much longer (approximately 3s) for the lerpFactor
to reach 1
(I used 0.99
to because it will never actually reach 1
, just get very close).
I thought the reason for this might be that the Mathf.SmoothDamp()
uses Time.deltaTime
by default, which maybe doesn't work inside coroutines. So I tried supplying my own value:
private IEnumerator ReachTarget()
{
_speed = 0f;
var lerpFactor = 0f;
var startingPosition = transform.position;
var startingRotation = transform.rotation;
var prevTime = Time.realtimeSinceStartup;
while (lerpFactor < 0.99f)
{
var time = Time.realtimeSinceStartup - prevTime;
prevTime = Time.realtimeSinceStartup;
lerpFactor = Mathf.SmoothDamp(lerpFactor, 1f, ref _speed, 1f, maxSpeed: 1000f, time); // using 1000f for max speed
transform.position = Vector3.Lerp(startingPosition, _targetTransform.position, lerpFactor);
transform.rotation = Quaternion.Lerp(startingRotation, _targetTransform.rotation, lerpFactor);
yield return null;
}
transform.position = _targetTransform.position;
transform.rotation = _targetTransform.rotation;
}
This didn't change anything and it takes the same amount of time for the lerpFactor
to reach 1
.
How can I make it work as it's supposed to?