Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Public class EnemySpawner : MonoBehaviour
- {
- public GameObject enemyPrefab;
- public float width = 10;
- public float height = 5;
- public float speed = 10f;
- private bool movingRight = true;
- private float maxX;
- private float minX;
- // Use this for initialization
- void Start ()
- {
- // Calculate the Boundary of the screen
- 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));
- maxX = rightBoundary.x;
- minX = leftBoundary.x;
- // Loop through every item in the collection to create an enemy on the positions.
- 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, 0));
- }
- // Update is called once per frame
- void Update()
- {
- // Check if the formation is going outside of the play space.
- float rightEdgeOfFormation = transform.position.x + (0.5f * width);
- float leftEdgeOfFormation = transform.position.x - (0.5f * width);
- // Set the formation to move left or right between the limits of the edges
- if (movingRight)
- {
- transform.position += Vector3.right * speed * Time.deltaTime;
- }
- else
- {
- transform.position += Vector3.left * speed * Time.deltaTime;
- }
- // Switch the direction of the formation
- if (leftEdgeOfFormation < minX)
- {
- movingRight = true;
- }
- else if (rightEdgeOfFormation > maxX)
- {
- movingRight = false;
- }
- if (AllMembersDead())
- {
- Debug.Log("Empty formation!");
- }
- }
- bool AllMembersDead()
- {
- foreach (Transform childPositionGameObject in transform)
- {
- if (childPositionGameObject.childCount > 0)
- {
- return false;
- }
- }
- return true;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement