Using Raycast to Detect Attacks and Dodge

2D Space Shooter — Phase II: Core Programming Challenges

Dennisse Pagán Dávila
3 min readSep 6, 2021

Objective: Detect a projectile Player Attack and move the Enemy(dodge) out of the way to avoid the shot.

Note: In the previous article, I introduced Raycasting. This article will be using some of the logic explained there.

Detect an Object’s Position Using Raycast

  1. First, we need to declare our global variables.
  • The distance is the length of the Ray
  • The Ray Cast Rad or Raycast Radius is a variable that will be needed later on when using Physics2D.CircleCast. This variable is a SerializeField so that you can tweak its value from the Inspector if necessary.

2. Now we can create our Raycast. The syntax follows closely to the one discussed in the previous article. However, this time around we will be using a Physics2D.CircleCast in addition to our regular RaycastHit2D logic.

How does Physics2D.CircleCast work?

This function returns a RaycastHit2D object with a reference to the Collider that the box has hit. If nothing was struck, the Collider property of the result will be NULL. Layermasks can be used to detect only the specific objects within a give mask making it easy to ignore the object that don’t need to be detected.

  • transform.position: The current position of the object from where the Ray will cast.
  • Vector2.Down: is the direction in which the ray is being cast.

3. Since the Physics2D.CircleCast function returns information if it intercepts any colliders, we can compare the detected objects to our desired search as long as it isn’t null.

Now, we can perform the dodging logic within the if-statement.

Randomizing the Dodge Movement

There are various ways to implement a dodge logic for an object, I personally decided to randomize the position of the Enemy to give the impression of it teleporting within the map.

  1. In order to achieve this effect, you simply need two randomized variables to retain the axis information.

2. Randomize the position as a new vector.

The Result:

This article has been part of a series of Core Programming Challenges from GameDevHQ. In the article, I will be taking on the challenge of creating an enemy that can detect when it’s behind the Player and fire at them!

--

--

Dennisse Pagán Dávila

Software Engineer that specialize in Game Development. Currently looking for new opportunities. Portfolio: dennissepagan.com