About 'Make Enemy Shoot'!

In this video (objectives)…

  1. Instantiate laser and provide it velocity in negative y direction.
  2. Create new laser prefab for the enemy to shoot.

After watching (learning outcomes)…

Make the enemy shoot projectiles at random time intervals.

(Unique Video Reference: 21_LD_CUD)

We would love to know…

  • What you found good about this lecture?
  • What we could do better?

Remember that you can reply to this topic, or create a new topic. The easiest way to create a new topic is to follow the link in Resources. That way the topic will…

  • Be in the correct forum (for the course).
  • Be in the right sub-forum (for the section)
  • Have the correct lecture tag.

Enjoy your stay in our thriving community!

Was curious why you opted to push through update for a counter rather than use a coroutine for enemy firing. Is there a noticeable performance difference between the 2?

    private IEnumerator OnBecameVisible()
    {
        yield return new WaitForSeconds(Random.Range(0f, projectileFiringPeriod));
        StartCoroutine("FireContinuously");
    }

    private void OnBecameInvisible()
    {
        StopCoroutine("FireContinuously");
    }

    private IEnumerator FireContinuously()
    {
        while (true)
        {
            var weaponPos = new Vector2(transform.position.x + weaponXOffset, transform.position.y + weaponYOffset);
            var laser = Instantiate(laserPrefab, weaponPos, Quaternion.identity) as GameObject;

            var rigidbody = laser.AddComponent<Rigidbody2D>();
            rigidbody.velocity = new Vector2(0f, Random.Range(-projectileSpeed / 2, -projectileSpeed));
            rigidbody.gravityScale = 0f;

            AudioSource.PlayClipAtPoint(laserSound, Camera.main.transform.position);
            yield return new WaitForSeconds(Random.Range(projectileFiringPeriod / 2, projectileFiringPeriod));
        }
    }

Mostly, from a learning perspective, to show a different approach. Using a coroutine is fine. In terms of performance, counting down on update is pretty low impact.

2 posts were split to a new topic: Why do my lasers spawn multiple times?

Privacy & Terms