Completely Different Approach

I took a different approach to the playfield size, enemies and how to update safely and never encountered the issue demonstrated.

On enemy creation I determined the min and max X position, and adjusted using the sprite extent. Then using these values I calculated the max and min X movements.

the code for this was as follows

float spriteMaxX = -500.0f;
float spriteMinX = 500.0f;
GameObject newEnemy = null;

foreach ( Transform child in transform )
{
  newEnemy = Instantiate( EnemyPrefab, child.transform.position, Quaternion.identity ) as GameObject;
  newEnemy.transform.parent = child.transform;
  if ( child.transform.position.x > spriteMaxX )
  {
   spriteMaxX = child.transform.position.x;
  }
  else if ( child.transform.position.x < spriteMinX )
  {
    spriteMinX = child.transform.position.x;
  }
}

SpriteRenderer renderer;
if ( newEnemy != null )
{
  renderer = newEnemy.GetComponent<SpriteRenderer>();
  spriteMinX -= renderer.bounds.extents.x;
  spriteMaxX += renderer.bounds.extents.x;
}
Vector3 wp;
float z = transform.position.z - Camera.main.transform.position.z;
wp = Camera.main.ViewportToWorldPoint( new Vector3( 0.0f, 0.0f, z ) );
minX = wp.x - spriteMinX;
wp = Camera.main.ViewportToWorldPoint( new Vector3( 1.0f, 1.0f, z ) );
maxX = wp.x - spriteMaxX;

I also declared a Vector3 called _direction and set to Vector3.right initially.

In update I then did the following:

  void Update()
  {
    Vector3 enemyPos = transform.position;
    enemyPos += _direction * Speed * Time.deltaTime;
    if ( enemyPos.x >= maxX )
    {
      _direction = Vector3.left;
    }
    else if ( enemyPos.x <= minX )
    {
      _direction = Vector3.right;
    }
    enemyPos.x = Mathf.Clamp( enemyPos.x, minX, maxX );
    transform.position = enemyPos;
  }

The clamp prevents the enemies exiting the play space, the positioning of enemies means they always move hard to the left or right of the screen and no sticking issues either.

Further on, as enemies are destroyed on the left or right, a quick recalculation of the min and max means the remaining enemies can move further to the left and right, just like classic space invaders games do.

4 Likes

Privacy & Terms