- Home /
The question is answered, right answer was accepted
How to stop MoveTowards teleporting
I am trying to make a zombie walk around randomly when it doesn't sense the player, but for some reason it is teleporting instead of walking smoothly. I have tried using Lerp but that seems to crash my Unity. The first movement works fine just the second one in the while loop does not work. This is the code I have currently:
void Update () {
// Find XY of player
playerPos = new Vector2 (player.transform.position.x, player.transform.position.y);
// If player is in vision then follow player
if (playerInRange == true) {
transform.position = Vector2.MoveTowards (transform.position, playerPos, speed * Time.deltaTime);
}
// Else move randomly
else {
if (randomTrue) {
StartCoroutine (delay ());
Debug.Log("delayDone");
}
}
}
IEnumerator delay () {
randomTrue = false;
// Find random location near zombie
randomMovement = new Vector2 (transform.position.x + Random.Range(-4.0f,4.0f), transform.position.y + Random.Range(-4.0f,4.0f));
// While zombie is not at chosen location move towards location
while (transform.position.x != randomMovement.x && transform.position.y != randomMovement.y){
transform.position = Vector2.MoveTowards (transform.position, randomMovement, speed * Time.deltaTime);
}
Debug.Log ("startWait");
// Delay between random movements
yield return new WaitForSeconds (Random.Range(2.0f, 7.0f));
Debug.Log ("endWait");
randomTrue = true;
}
Any help would be appreciated, thank you.
3, and it works nicely for the first $$anonymous$$oveTowards, just not the second.
Answer by kingartur3 · Oct 10, 2017 at 12:47 AM
Not sure if correct, but try to change this loop:
while (transform.position.x != randomMovement.x && transform.position.y != randomMovement.y){
transform.position = Vector2.MoveTowards (transform.position, randomMovement, speed * Time.deltaTime);
}
Adding a Wait:
while (transform.position.x != randomMovement.x && transform.position.y != randomMovement.y){
transform.position = Vector2.MoveTowards (transform.position, randomMovement, speed * Time.deltaTime);
yield return new WaitForSeconds (0.5f);
}
Maybe change the 0.5f if it works but it's jerky.
This worked, thanks. I changed the 0.5f to 0.008333f so that it tries to move every 1/2 a tick which stopped any jerking. When I put it to move every 1 tick there was still some visible jerking.
Don't use WaitForSeconds in this case. Just use yield return null;
ins$$anonymous$$d. Time.deltaTime only makes sense when you actually use it every frame.
btw: WaitForSeconds can't be faster than the framerate. If you wait 0.00000001 seconds it will still wait at least one frame. You can't wait "half" a frame.
Follow this Question
Related Questions
Making a bubble level (not a game but work tool) 1 Answer
Multiple Cars not working 1 Answer
2d obstacle moving up and down question 1 Answer
Distribute terrain in zones 3 Answers
How to create 2D random movement? 1 Answer