[Solved] Enemy Formation Keeps moving Left

Hello,
As the title points out i have an issue where the enemy formation doesn’t stop at the left edge of the camera. The formation keeps going to maybe 4 or 5 times the width before turning back. This doesn’t happen with the right edge.
Below is the code for the enemyFormation script.
Thank you in advance.

,
public class EnemySpawner : MonoBehaviour {
public GameObject enemyPrefab;
public float Width = 10f;
public float Hight = 10f;
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 rightEdge = Camera.main.ViewportToWorldPoint (new Vector3(1f,0, distanceToCamera));
Vector3 leftEdge = Camera.main.ViewportToWorldPoint (new Vector3(-1f,0, distanceToCamera));

xmax = rightEdge.x;
xmin = leftEdge.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,Hight));
}


// Update is called once per frame
void Update ()
{
	if (MovingRight) {
		transform.position += Vector3.right * speed * Time.deltaTime;
	} else {
		transform.position += Vector3.left * speed * Time.deltaTime;
	}

	float RightEdgeOfFormation = transform.position.x + (0.5f * Width);
	float LeftEdgeOfFormation = transform.position.x - (0.5f * Width);

	if (RightEdgeOfFormation > xmax) {
		MovingRight = false;
	} else if (LeftEdgeOfFormation < xmin) {
		MovingRight = true;
	}


	
}

,

Hi @uhadi,

The viewport space is normalized and ranges between 0,0 and 1,1, change the -1f to a 0f in this line;

    Vector3 leftEdge = Camera.main.ViewportToWorldPoint(new Vector3(0f, 0f, distanceToCamera));

Please let me know if this resolves the issue. :slight_smile:


See also;

It did
Thank you very much :slight_smile:

Sorry I keep missing these tiny bits

All the best

1 Like

Hi Yusuf,

Great, and there is absolutely nothing to apologise for, learning through little mistakes is still learning, so it’s all very worth while :slight_smile:

Privacy & Terms