Movement and Direction script bugging out
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);
}
}
Answer by FreeStyled · Jun 03, 2016 at 05:12 PM
OK, I've managed to solve my issue by wrapping everything inside Update() in an if statement and control what's being done by a bool. My finished Update() function looks like this:
void Update()
{
if (!isWaiting)
{
currentPosition = transform.position;
Vector3 targetRotation = endPosition - transform.position;
Vector3 newDir = Vector3.RotateTowards(transform.forward, targetRotation, (10 * Time.deltaTime), 0.0f);
transform.rotation = Quaternion.LookRotation(newDir);
transform.position = Vector3.Lerp(startPosition, endPosition, ((Time.time - startTime) * speed) / journeyLength);
if (currentPosition == endPosition)
{
isWaiting = true;
Invoke("ResetMovement", waitTime);
}
}
}
Where the bool isWaiting is set to false on Start. Thanks to /u/darkon76 on Reddit for helping me out with this and suggesting I could also use a State Machine in order to have more control of the states.