New Enemy Type using Raycast

Annoying Enemy that will destroy PowerUps

Raycast

To detect the powerup in front of the enemy we will be using Raycast.

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.

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
void Update()
{
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
Debug.Log(hit.transform.tag);
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.

--

--

--

Aspiring developer that’s self-learning Unity & C# to transition to a career with Unity. I got a passion for creating interactive experiences.

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

How to Build an App without Coding?

A quick look into Javascript, Python, Go and C++

What happens when you type holbertonschool.com in your browser and press Enter

Sierpiński Triangle

Serverless Data Extraction with AWS

Get rolling with Spring MVC

Getting Started with Spring MVC

What are the Advantages of Using Laravel?

Ubuntu 20.04 LTS Released! Focal Fossa is Out — Tec Robust

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Tristan Engel

Tristan Engel

Aspiring developer that’s self-learning Unity & C# to transition to a career with Unity. I got a passion for creating interactive experiences.

More from Medium

ESP8266 Smart Thermostat (Huzzah+ DataCake) with SMS Alerts

Automate Player Input with Unity Test Runner and NSubstitute

2-Day Linux Training

Moving Platform