I followed the script completely but the enemy ships go off the screen and don’t come back. Help please here is my script.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyFormation : MonoBehaviour {
public GameObject enemyPrefab;
public float width = 7f;
public float height= 5f;
public float speed = 5f;
private bool movingRight = true;
private float xmax;
private float xmin;
// Use this for initialization
void Start () {
float distanceToCamera = transform.position.z - Camera.main.transform.position.z;
Vector3 leftBoundary = Camera.main.ViewportToWorldPoint(new Vector3(0,0, distanceToCamera));
Vector3 rightBoundary = Camera.main.ViewportToWorldPoint(new Vector3(1,0, distanceToCamera));
xmax = rightBoundary.x;
xmin = leftBoundary.x;
foreach ( Transform child in transform) {
GameObject enemy = Instantiate(enemyPrefab, child.transform.position, Quaternion.identity) as GameObject;
enemy.transform.parent = child;
}
}
public void OnDrawGizmos () {
Gizmos.DrawWireCube(transform.position, new Vector3 (width, height));
}
// Update is called once per frame
void Update () {
if (movingRight) {
transform.position += new Vector3 (speed * Time.deltaTime,0);
} else {
transform.position += new Vector3 (speed*Time.deltaTime,0);
}
float rightEdgeOfFormation = transform.position.x + (0.5f*width);
float leftEdgeOfFormation = transform.position.x - (0.5f*width);
if (leftEdgeOfFormation < xmin) {
movingRight = true;
}else if (rightEdgeOfFormation > xmax){
movingRight = false;
}
}
}