- Home /
Random Movement Problem
Hey guys this script worked perfectly last time I ran it but now it suddenly stopped working. I havent changed anything, is there an update that has deprecated some of this and can someone help me rework it if so?
I have 6 trees as a possible location which i assign in the editor
[SerializeField] private float _speed = 32f; private float _closeThreshold = .1f; [SerializeField] private Transform[] _treeTopLocations;
//The position we want to move to
private Vector3 _targetPos;
void Start()
{
//Set our first target location to where we already are
_targetPos = transform.position;
StartCoroutine(MonkeyMovement());
}
void Update()
{
//If we aren't close to our target location
if (Vector3.Distance(transform.position, _targetPos) > _closeThreshold)
{
//Find the direction from where we are to where we want to be
//Normalize it to get a direction rather than the whole distance
Vector3 _currentDir = (_targetPos - transform.position).normalized;
//Move towards the target
transform.Translate(_currentDir * _speed * Time.deltaTime);
}
}
IEnumerator MonkeyMovement()
{
while (GameManager.gameManager.gameOver == false)
{
if (UIManager.uIManager.pauseMenuVisible == true)
{
yield return null;
}
else
{
//Dont get a new target for 2 seconds
yield return new WaitForSeconds(1);
//Get a new target
Transform newTree = TreeTopLocations();
_targetPos = newTree.position;
}
}
}
Answer by WarmedxMints · Sep 24, 2019 at 04:31 AM
Why are you changing the target location every second when the object may be nowhere near the target by then? Really you find the next target once it as reached the destination.
Other than that, are you getting any errors due to your use of singletons or from the TreeTopLoations method?
no I'm getting no errors (which is the frustrating part)
I am changing the target every second because the time it takes the monkey to change targets is less than a second.
The distance it travels is completed in less than 1 second. do you think increasing the amount of time it remains at 1 location would fix my problem?
hey make you comment an answer, you were right about the "prefab" not being close enough to the destination before looking for another destination. Didn't throw an error which is why i didn't think that as a problem. Thanks
Your answer
Follow this Question
Related Questions
AI repeats movement and isnt randomised 0 Answers
Creating a random movement script for multiple AI drivers 2 Answers
2D Random AI 1 Answer
Random direction with Mouse Click... 2 Answers
Racing Ai? long read 1 Answer