Problem not fixed

My formation moves off the screen to the right, and keeps going, however when I manually set the bool to false, it starts moving back when the middle point of the formation reaches the edge then turns back around again, getting stuck off the screen, here’s my code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EnemySpawner : MonoBehaviour {
public GameObject enemyPrefab;

public float width = 10f, height = 5f, speed = 5f;

private float xmax, xmin;

public bool movingRight = true;

// Use this for initialization
void Start () {
    float distanceToCamera = transform.position.z - Camera.main.transform.position.z;

    Vector3 rightBoundary = Camera.main.ViewportToScreenPoint(new Vector3(1, 0, distanceToCamera));
    xmax = rightBoundary.x;

    Vector3 leftBoundary = Camera.main.ViewportToScreenPoint(new Vector3(0, 0, distanceToCamera));
    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 += 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 (leftEdgeOfFormation < xmin)
    {
        movingRight = true;
    } else if (rightEdgeOfFormation > xmax)
    {
        movingRight = false;
    }
}

}

Hi Recable,

The problem is probably with the left and right boundaries, which are set via the ViewportToScreenPoint() method. You should use the ViewportToWorldPoint() method instead, to get coordinates in world space.

Urg thank you, I entered the wrong “quick” code by accident, thanks!