- Home /
Trouble with Moving an Enemy back and forth
So I made a enemy walk back and forth using IEnumerator
public float speed;
Rigidbody2D rbody;
public float timer;
public float directionx;
public float directiony;
public bool canMove = true;
// Use this for initialization
void Start () {
rbody = GetComponent<Rigidbody2D> ();
StartCoroutine (Move(timer));
}
IEnumerator Move(float timer){
if (!canMove) {
rbody.velocity = Vector2.zero;
yield break;
}
while (canMove == true) {
Vector2 targetVelocity = new Vector2 (directionx, directiony);
rbody.velocity = targetVelocity * speed;
yield return new WaitForSeconds (timer);
Vector2 targetVelocity1 = new Vector2 (-directionx, -directiony);
rbody.velocity = targetVelocity1 * speed;
yield return new WaitForSeconds (timer);
}
}
}
However, my problem is I want the enemy to stop immediately when killed hence the canMove bool. With my current code, when I fire off the canMove bool, the enemy won't stop and is stuck forever moving one way. I can kinda see why this is happening but I'm not sure how to fix it. Maybe IEnumerators isn't the right way to go? Any help is greatly appreciated.
Answer by Hellium · Apr 29, 2019 at 06:05 AM
Indeed, using a coroutine here may not be the best option, unless you add a while( true )
around the body of the function. I suggest you the FixedUpdate
instead.
Following code not tested:
public float speed;
Rigidbody2D rbody;
float time;
public float timer;
public float directionx;
public float directiony;
public bool canMove = true;
// Use this for initialization
void Start () {
rbody = GetComponent<Rigidbody2D> ();
}
private FixedUpdate()
{
if (!canMove)
{
rbody.velocity = Vector2.zero;
return;
}
Vector2 targetVelocity = Mathf.Repeat( time, timer * 2 ) < timer ?
new Vector2 (directionx, directiony) :
new Vector2 (-directionx, -directiony);
rbody.velocity = targetVelocity * speed;
time += Time.fixedDeltaTime;
}
Thank you for answering! Everything is working fine except the enemy never changes direction(the timer doesn't go down either). I'm unfamiliar with $$anonymous$$athf.Repeat so I'm not sure how to fix it.
I forgot to increase time
variable my bad. I am on my mobile, so could not test it. Hope it fixes!
Your answer
![](https://koobas.hobune.stream/wayback/20220612200406im_/https://answers.unity.com/themes/thub/images/avi.jpg)