Why is my "enemies " leaving the screen?
What is wrong with my code using System.Collections; using System.Collections.Generic; using UnityEngine; public class EnemySpawner : MonoBehaviour { public GameObject enemyPrefab; public float width = 10.0f; public float height = 5f; public float speed = 1f; 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 LeftEdge = Camera.main.ViewportToWorldPoint(new Vector3(0, 0, distanceToCamera)); Vector3 RightEdge = Camera.main.ViewportToWorldPoint(new Vector3(1, 0, distanceToCamera)); xMax = LeftEdge.x; xMin = RightEdge.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; (samma sak)
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 = !movingRight;
}
if (rightEdgeOfFormation > xMax)
{
movingRight = !movingRight;
}
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612123947im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Camera Shaking problem(Blackthronprod) 0 Answers
Update and Get PlayerPrefs during runtime? 0 Answers
How to communicate between scripts and gameobject use tag in unity 1 Answer
Double Jump 2 Answers