Simple script. Trying to get a cube to move up and down repeatedly. However when the object starts moving it jerks up and then I end up with a smooth transition. What’s going on?
public class Cube : MonoBehaviour
{
public float max = 3f;
public float speed = 3f;
public float startTime;
// Use this for initialization
void Start()
{
max = transform.position.y + 3;
}
// Update is called once per frame
void Update()
{
StartCoroutine(StartMovement(startTime));
}
IEnumerator StartMovement(float time)
{
yield return new WaitForSeconds(time);
transform.position = new Vector3(transform.position.x, Mathf.PingPong(Time.time * speed, max), transform.position.z);
}
}
I changed it so the coroutine is only called once and instead use a bool to trigger the movement in update now. If I don’t use WaitForSeconds and just transform the position at start, there is no jerking motion. It seems this is causing the issue
public class Cube : MonoBehaviour
{
public float max = 3f;
public float speed = 3f;
public float startTime;
private bool start = false;
// Use this for initialization
void Start()
{
StartCoroutine(StartMovement(startTime));
}
// Update is called once per frame
void Update()
{
if (start)
{
transform.position = new Vector3(transform.position.x, Mathf.PingPong(Time.time * speed, max), transform.position.z);
}
}
IEnumerator StartMovement(float time)
{
yield return new WaitForSeconds(time);
start = true;
}
}
Thank you this solved the problem. I started digging into the Time.time documentation afterwards. Might be a good idea to familiarize myself a little more with Time when working with it.