The question is answered, right answer was accepted
Why my angle lerp code take only 30% time to finish?
Hello there, I'm trying making a game where camera slowing lerp to look at my ship, not look at it all the time instantly. My issue is, why my code only take 30% time to finish ? I know this because i put a Debug.Log there to count (elapseTime/time) and it only increase to 0.3 and the lerp finished, although the debug still continue to count to 1. Pls help enlighten me masters !
using UnityEngine;
using System.Collections;
public class CameraFollow : MonoBehaviour {
public Transform target ;
Transform camFollowPos;
float smooth = 3f;
// Use this for initialization
void Start () {
camFollowPos = target.FindChild ("camFollowPos");
}
// Update is called once per frame
void Update () {
transform.position = camFollowPos.position;
if(Input.GetKeyDown(KeyCode.Space))
{
StopCoroutine(LookatShipCoroutine(smooth));
StartCoroutine(LookatShipCoroutine(smooth));
}
}
IEnumerator LookatShipCoroutine(float time)
{
float elapsedTime = 0f;
while (elapsedTime < time) {
transform.rotation = Quaternion.Lerp( transform.rotation,camFollowPos.rotation,(elapsedTime/time));
elapsedTime += Time.deltaTime;
Debug.Log (elapsedTime / time);
yield return null;
}
}
}
http://answers.unity3d.com/questions/998544/having-difficulty-with-lerp.html#answer-998744
Two solutions
IEnumerator LookatShipCoroutine(float time)
{
Quaternion startRotation = transform.rotation ;
Quaternion endRotation = camFollowPos.rotation ;
for( float elapsedTime = 0f ; elapsedTime < time ; elapsedTime += Time.deltaTime )
{
transform.rotation = Quaternion.Lerp( startRotation,endRotation,(elapsedTime/time));
Debug.Log (elapsedTime / time);
yield return null;
}
}
IEnumerator LookatShipCoroutine(float time)
{
Quaternion endRotation = camFollowPos.rotation ;
for( float elapsedTime = 0f ; elapsedTime < time ; elapsedTime += Time.deltaTime )
{
transform.rotation = Quaternion.Lerp( transform.rotation,endRotation, Time.deltaTime );
Debug.Log (elapsedTime / time);
yield return null;
}
}
@Hellium Hi man, thanks for the answer ! Can you explain how your two solutions different than each other and my code ? I want to know more deeply. Why in your first solution the t = elapsedTime/time ( from 0 to 1 ) , but in the second -> the t = Time.deltaTime , i think this Time.deltaTime is always close to 0.02 ?
I think the main difference is that you shouldn't use transform.rotation inside the Lerp, because its value changes on each iteration.