Edit: I’m dumb and assigned xMax twice
Hi,
I’m having problem, whereby the enemies shake and pull in one direction but don’t move smoothly to one side and bounce. My code is below and I’ve tried the other fix mentioned in this discussion of changing the width and height of the box but still it isn’t working!
public class EnemySpawner : MonoBehaviour {
public GameObject enemyPrefab;
public float width = 10f;
public float height = 5f;
public float speed = 5f;
private bool movingRight = false;
private float xMax;
private float xMin;
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,1, distanceToCamera));
xMax = rightBoundary.x;
xMax = 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));
}
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 || rightEdgeOfFormation > xMax)
{
movingRight = !movingRight;
}
}
Cheers,