- Home /
How do I script enemy AI movement using Coroutines?
This is my code so far for my enemy AI, it will shoot bullets and move from left to right after it has entered the screen. There will be a lot of enemies on screen at the same time. I have no idea how to make it move in a sequence. If someone could help that would be great.
using UnityEngine; using System.Collections;
public class EnemyArmoredFighter : MonoBehaviour {
public float speed;
public float fireRate;
public int hitPoints;
int i;
int Damage;
// Use this for initialization
void Start () {
StartCoroutine("EnemyMoveDown");
}
// Update is called once per frame
void Update () {
while (hitPoints >=1){
StartCoroutine ("MovementSequence");
}
}
IEnumerator MovementSequence(){
StartCoroutine("EnemyMoveLeft");
StartCoroutine("EnemyMoveRight");
StartCoroutine("EnemyMoveRight");
StartCoroutine("EnemyMoveLeft");
}
IEnumerator EnemyMoveDown(){
for(i=1;i<300;i++)
{
transform.position += transform.up * -speed;
yield return new WaitForSeconds(3);
}
}
IEnumerator EnemyMoveLeft(){
for(i=1;i<300;i++)
{
transform.position += transform.right * -speed;
yield return new WaitForSeconds(3);
}
}
IEnumerator EnemyMoveRight(){
for(i=1;i<300;i++)
{
transform.position += transform.right * speed;
yield return new WaitForSeconds(3);
}
}
}
You don't need coroutines to move in a sequence. Can just use time variables, or a frame countdown.
If you really want to use them, step one of fixing that code is to delete everything (do you really want them to freeze in place for 3 seconds, then make one hop?) $$anonymous$$aybe find an example of a single coroutine, to get a feel for them.
Answer by Maerig · May 27, 2014 at 03:03 AM
Do you mean something like this ?
IEnumerator MovementSequence(){
yield return StartCoroutine("EnemyMoveLeft");
yield return StartCoroutine("EnemyMoveRight");
yield return StartCoroutine("EnemyMoveRight");
yield return StartCoroutine("EnemyMoveLeft");
}
Your answer
Follow this Question
Related Questions
Making a bubble level (not a game but work tool) 1 Answer
Distribute terrain in zones 3 Answers
Can't change the speed of a character. 2 Answers
adiing a wait betweem if statements 1 Answer
Z axis change 2 Answers