Hi,
So I’ve been trying to create a script which randomly moves a capsule from startpoint to endpoint with a pause in between each lerp and resets the start and end point values. I’ve managed to make it so that the capsule moves from start to end point and pauses for a random amount of time, but when it sets off again the capsule starts to “bug out” for a bit and then it resumes as normal. the amount of time the capsule “bugs out” for is equal to that of the random time that’s being set. Hopefully someone can pick up where I’ve gone wrong and explain it to me because so far I’ve found nothing like this on the forum.
using UnityEngine;
using System.Collections;
public class TestMovement : MonoBehaviour {
public Vector3 startPosition;
public Vector3 endPosition;
public Vector3 currentPosition;
public float speed;
private float startTime;
private float journeyLength;
public float waitTime;
void Start()
{
currentPosition = transform.position;
startPosition = new Vector3(Random.Range(-10f, 10f), 1.4f, Random.Range(-10f, 10f));
endPosition = new Vector3(Random.Range(-10f, 10f), 1.4f, Random.Range(-10f, 10f));
startTime = Time.time;
journeyLength = Vector3.Distance(startPosition, endPosition);
waitTime = Random.Range(1f, 10f);
}
void ResetMovement()
{
startPosition = transform.position;
endPosition = new Vector3(Random.Range(-10f, 10f), 1.4f, Random.Range(-10f, 10f));
startTime = Time.time;
journeyLength = Vector3.Distance(startPosition, endPosition);
}
void Update()
{
currentPosition = transform.position;
Vector3 targetRotation = endPosition - transform.position;
Vector3 newDir = Vector3.RotateTowards(transform.forward, targetRotation, (10 * Time.deltaTime), 0.0f);
if (currentPosition == endPosition)
{
Invoke("ResetMovement", waitTime);
}
transform.rotation = Quaternion.LookRotation(newDir);
transform.position = Vector3.Lerp(startPosition, endPosition, ((Time.time - startTime) * speed) / journeyLength);
}
}