Crafting a Dodge System in Unity using Linecast

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.




Unity Developer

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

Recommended from Medium

10 Interview Topics About Java Script

Interacting with REST APIs in Quarkus

CrossDC monitoring with DC/OS and Prometheus

Top 5 Software Testing Trends for 2018

Implementing call-by-reference and call-by-name in Lua

Making Philosophy Reality

How to set up a Redis Cluster with TLS in a local machine

How to set up a Redis Cluster with TLS in a local machine

Complete Flutter Basics

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
Mike Brisson

Mike Brisson

Unity Developer

More from Medium

’Twas The Code Before Christmas

[ SDL2 — Part 2 ] Your first SDL2 application

Day 19 of my Developer Journey: Creating the Shield Powerup logic

Bit Manipulation and two’s complement