Make Sure We Hit the Floor- Game Dev Series 100

Objective: use Physics2D.Raycast on specific layer.

When we using Raycast as colliding detection, it returns the first result no matter what it is. That would cause some problems.
For example, when I create a ground touching detection by using Raycasthit, it keep return the collider of Player as result. I need to make the Raycast ignore Player, more so, I need to make Raycast only return the result on specific layer.

Raycast hit the collider of Player

Set the layer of ground

First, lets create a layer to all the ground. Select the floor objects and select Add Layer. The first blank column you can add should be on №8.

Once you type in “Ground”, you successfully set the floors to layer Ground.
Now we need to make our Player can only return this layer.

Set layer mask

Inside the script doing Raycast, you will see it says that using “int” as layerMask.

However, we could not use “8” as the integer in code. It use binary as the layer order in Unity. To explain this more clearly, here is a simple drawing about this concept.

In binary, layer 8 actually means moving the “1” 8 times to the left from very right. The result in binary would be from "000000001" to “100000000”. To present this result in code, we can use “1 << 8" as value of layerMask.

Once using layerMask to Raycast, it should no longer return the value of Player but the ground layer.

Raycasthit2D successfully hit the floor

As we already know the meaning of “1 << 8" in code, we can actually use the integer of binary “100000000" to decimal, which is 256.

You should get the same result.

Now Raycast on wrong object will no longer be a problem.




A passionate gamer whose goal is to work in video game development.

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

Recommended from Medium

Top Python Web Development Frameworks for 2022

Set Your Software Implementation Up For Success

Back End Development with Rails

How Elevators Know Which Floors to Go to

Send Email Attachment from Redshift query (PostgreSQL) with Python

Using OpenCV with Gazebo in Robot Operating System (ROS) — Part 0 — Getting everything set up

How to Implement Elasticsearch When Developing a Rails Web App

How to Speed Up Data Scraping Application with Concurrency in Python

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
S.J. Jason Liu

S.J. Jason Liu

A passionate gamer whose goal is to work in video game development.

More from Medium

How I used scriptable objects to build a powerup system

OnClick Event in Unity

Day 105: Working with Animation Events in Unity

Creating A Respawn/Checkpoint System In Unity