I don’t know what happened, but all of the sudden, when I changed my code so that enemies appear one at a time, it also had the unusual effect of triggering the bug where they get stuck on the side. I’m not sure what I did to cause this.
Here is my EnemySpawner code:
using UnityEngine;
using System.Collections;
public class EnemySpawner : MonoBehaviour {
public GameObject enemyPrefab;
public float width = 10f;
public float height = 5f;
public float enemySpeed = 0.1f;
public float spawnDelay = 0.5f;
private bool direction = false;
private float xMin;
private float xMax;
// Use this for initialization
void Start () {
SpawnUntilFull();
}
public void OnDrawGizmos(){
Gizmos.DrawWireCube(transform.position, new Vector3(width, height, 0));
}
// Update is called once per frame
void Update () {
if(direction == true){
transform.position += Vector3.right * enemySpeed * Time.deltaTime;
} else if(direction == false){
transform.position += Vector3.left * enemySpeed * Time.deltaTime;
}
float rightEdgeOfFormation = transform.position.x + 0.5f * width;
float leftEdgeOfFormation = transform.position.x - 0.5f * width;
if(leftEdgeOfFormation < xMin){
direction = true;
} else if(rightEdgeOfFormation > xMax){
direction = false;
}
if(AllMembersDead()){
Debug.Log("Empty Formation");
SpawnUntilFull();
}
}
void SpawnNewSquad(){
float distanceToCamera = transform.position.z - Camera.main.transform.position.z;
Vector3 leftEdge = Camera.main.ViewportToWorldPoint(new Vector3(0,0, distanceToCamera));
Vector3 rightEdge = Camera.main.ViewportToWorldPoint(new Vector3(1,0, distanceToCamera));
xMax = rightEdge.x;
xMin = leftEdge.x;
foreach(Transform child in transform){
GameObject enemy = Instantiate(enemyPrefab, child.transform.position, Quaternion.identity) as GameObject;
enemy.transform.parent = child;
}
}
void SpawnUntilFull(){
Transform freePosition = NextFreePosition();
if(freePosition){
GameObject enemy = Instantiate(enemyPrefab, freePosition.position, Quaternion.identity) as GameObject;
enemy.transform.parent = freePosition;
}
if(NextFreePosition()){
Invoke("SpawnUntilFull", spawnDelay);
}
}
Transform NextFreePosition(){
foreach(Transform childPositionGameObject in transform){
if(childPositionGameObject.childCount == 0){
return childPositionGameObject;
}
}
return null;
}
bool AllMembersDead(){
foreach(Transform childPositionGameObject in transform){
if(childPositionGameObject.childCount > 0){
return false;
}
}
return true;
}
}
Thank you for your help!
