Skip to content

Instantly share code, notes, and snippets.

@bricef
Forked from Jaandlu/gist:71f1a3f14df43a523dad
Last active August 29, 2015 14:21
Show Gist options
  • Save bricef/839fa20866bbac3474cb to your computer and use it in GitHub Desktop.
Save bricef/839fa20866bbac3474cb to your computer and use it in GitHub Desktop.
Update on boundary code
using UnityEngine;
using System.Collections;
public class FormationController : MonoBehaviour {
public GameObject enemyPrefab;
public float width = 10;
public float height = 5;
public float speed;
public float padding;
private float xmin;
private float xmax;
private bool movingRight = true;
void Start () {
// calculate the boundaries from teh camera
float distance = transform.position.z - Camera.main.transform.position.z;
Vector3 leftMost = Camera.main.ViewportToWorldPoint(new Vector3( 0,0,distance));
Vector3 rightMost = Camera.main.ViewportToWorldPoint(new Vector3( 1,0,distance));
xmin = leftMost.x + padding;
xmax = rightMost.x - padding;
// spawn a new enemy for every position
foreach(Transform child in transform){
GameObject enemy = Instantiate(enemyPrefab, child.transform.position, Quaternion.identity) as GameObject;
enemy.transform.parent = child;
}
}
void OnDrawGizmos(){
float gizmoWidth, gizmoHeight;
gizmoWidth = transform.position.x + 0.5f * width;
gizmoHeight = transform.position.y + 0.5f * height;
Gizmos.DrawWireCube(new Vector3(0,5,0), new Vector3(gizmoWidth, gizmoHeight,0 ));
}
void Update () {
// move the formation
if (movingRight) {
transform.position += Vector3.right * speed * Time.deltaTime;
}else{
transform.position += Vector3.left * speed * Time.deltaTime;
}
// flip the direction if we're outside the boundaries.
if (transform.position.x < xmin || transform.position.x > xmax){
movingRight = !movingRight;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment