Another way for moving the enemies

using UnityEngine;
using System.Collections;

public class EnemySpawner : MonoBehaviour {

public GameObject enemyPrefab;
public int width = 10;
public int hight = 5;
public int speed = 4;

float xmin, xmax;


// Use this for initialization
void Start () {
    
    foreach(Transform child in transform)
    {
        GameObject enemy = Instantiate(enemyPrefab, child.transform.position, Quaternion.identity) as GameObject;
        enemy.transform.parent = child;
    }

    CalculateBoundaries();        
}

public void OnDrawGizmos()
{
    Gizmos.DrawWireCube(transform.position, new Vector3(width, hight));
}
	
void FixedUpdate()
{
    if (transform.position.x <= xmin || transform.position.x >= xmax)
    {
        speed *= -1;
    }
    transform.position += Vector3.left * speed * Time.deltaTime;
}

void CalculateBoundaries()
{
    float dist = transform.position.z - Camera.main.transform.position.z;
    Vector3 leftmost = Camera.main.ViewportToWorldPoint(new Vector3(0, 0, dist));
    Vector3 rightmost = Camera.main.ViewportToWorldPoint(new Vector3(1, 0, dist));
    xmin = leftmost.x + width / 2 + 0.5f;
    xmax = rightmost.x - width / 2 - 0.5f;
}

}

Privacy & Terms