New Enemy Type using Raycast
Annoying Enemy that will destroy PowerUps
To detect the powerup in front of the enemy we will be using Raycast.
How do you use documentation throughout your workflow? Share your experience with us by taking this survey. Suggest a…
Raycast will draw a line from an origin point into a set direction. Optionally you can set a max distance on the ray.
To store the information about what is being hit first with the Raycast we use RaycastHit2D.
How do you use documentation throughout your workflow? Share your experience with us by taking this survey. struct in…
Enemy Attack Powerup Script
The bold part is the part that matters. The rest depends on how your game is build. The _offset is to prevent the raycast hitting the enemy himself. Without the offset the raycast would return the enemy itself as first hit collider.
(The GetComponent in Update() is something that will be replaced in the future)
public class EnenmyAttackPowerUpStraight : MonoBehaviour
[SerializeField] private float _fireRate = 1f;
private float _nextFire = 0f;
[SerializeField] private GameObject _enemyLaser;
private Vector3 _offset = new Vector3(0, -0.9f, 0);
private bool _isAlive = true;
// Update is called once per frame
if (_isAlive) // double check to prevent bug that executes while loop while enemy is already dead
if (GetComponent<PolygonCollider2D>() != null)
RaycastHit2D hit = Physics2D.Raycast(transform.position + _offset, Vector2.down);
// If it hits tag PowerUp
if (hit.transform.tag == "PowerUp" && Time.time > _nextFire)
_nextFire = Time.time + _fireRate;
Instantiate(_enemyLaser, transform.position + _offset, Quaternion.identity);
Update Powerup Script
Make sure to update Powerup script OnTriggerEnter2D to detect collision with an enemy projectile and destroy the powerup game object on hit.