Https://community.gamedev.tv/t/having-issues-with-the-script/30004

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;
}

}
}

evening,

just wondering, in Update() when your not moving right should you be deducting the x transform in the else clause?

transform.position -= new Vector3 (speed*Time.deltaTime,0);

what is the speed set to? if the speed is slowed down, does it still go off screen?
whats the xMin and xMax set to?

1 Like

hehe, was about to say the same thing… Bryce actually had this, at least later on in the section;

        if (movingRight)
        {
            transform.position += Vector3.right * speed * Time.deltaTime;    // note: Vector3.right
        }
        else
        {
            transform.position += Vector3.left * speed * Time.deltaTime;    // note: Vector3.left
        }

Issue introduced in lecture 109 @ 07:43
Code changed to the above @07:48, features also in lecture 110, @ 01:37


See also;

1 Like

Thank you so much Rob it is working perfectly!

1 Like

No worries, glad you can move forward again :slight_smile:

Privacy & Terms