Crafting a Dodge System in Unity using Linecast

Mike Brisson
2 min readMay 1, 2021

--

One method for increasing difficulty in your game comes from adding simple AI. Giving enemies the ability to dodge your bullets can be one of the easier ways to achieve this.

Depending on the size of your projectiles, using a Raycast might be a solution. The problem you can run into is if the bullets you are firing off are barely the width of the ray that’s searching for them, you will either need an exact shot or multiple raycasts. This is where a linecast comes in handy.

In my 2D space shooter, I want to have a horizontal line in front of my enemy which can detect a laser hit and pass that info into a RaycastHit2D.

In the following example, I use a simple linecast between 2 points in space in front of the enemy:

I’m using the center of the enemy for my position. For the start position of the linecast, I’m offsetting the x axis by -0.5f, and the end position by 0.5f; This gives me a horizontal line in front of the enemy (perpendicular to any incoming lasers).

I then need to check if the object that hit the linecast was a laser and act accordingly:

As you can see, I’m also checking to see if the position of the hit is on the left or right. This way the enemy has the best chance to dodge … move left if the lincast was hit on right, and move right if the linecast was hit on left.

This allows you to avoid multiple colliders and the more advanced Boxcast which can add unnecessary overhead.

--

--

No responses yet