You’re Grounded! — A Quick Guide to Writing a Modular Ground Check Tool In Unity 2D
In this article, I will go over how to add a modular ground check script for a 2D game in Unity.
The functionality we are going to create is something I save in my utilities folder for use in any of my 2D games. The advantage is that the script can check as many points of contact as you want to add.
The first step is to create a new script. Mine is called GroundCheckUtility2D.
I have created several variables.
I will explain the purpose of each variable:
· _sensors: This is an array of transforms, each transform is a point of which contact is checked. In our example, we are going to have 2 — one for each foot but this can be as many or little as you require.
· _groundCheckLayerMask: This is a layer mask the user can define the raycast interaction to occur with — for example, you could have a layer mask for ground and enemies so you would be able to jump on enemies and the ground tiles.
· _groundCheckDistance: this is the max distance you will cast from the sensor.
· _groundHit and _groundMiss: These are optional, we assign colours to them and use them when we draw (debug)lines to show if we hit the ground or not.
· IsGrounded: this is a property that we can access from other scripts.
The next step in the script is to raycast and check for a collision. This function will take a transform as a parameter and return a bool, so we can use it for all our sensors.
We cast a ray based on the layer mask and if we hit a collider we draw a ray using our previously defined “hit” colour and return true. If we miss we use our missed colour and return false.
Next, we create a bool return type function that will cause each of our sensors to be passed into our raycast function. I have called this function RaycastFromAllSensors.
Now in update, we can set our IsGrounded property to the return value of our RaycastFromAllSensors function.
Next, we can set it up in our scene. Create an empty game object as a child of the object you want to ground check for (in my case the player) and call it an appropriate name e.g Ground_Check_Sensor_Right. Tip- You can change the icon so it's easier to see in the scene view.
We now want to have the sensors forward direction point in the direction we want to raycast. I will repeat this method for my left side.
Now go to the parent object and click “Add Component”. You can now search for your script and attach it.
Assign the sensors to the array and set your layer mask.
Now we can set the colours up. I did mine as green for a hit and red for a miss. Make sure to adjust the alpha on the colours as it defaults at 0 (fully transparent).
Now, all we need to do is test our functionality.
That’s all for now.