In our other article, we managed to create our Player Sprite, and paint our map but there’s one thing still to be done: when we run the game, the player goes through the ground! How do we fix that and make our ground solid?
On your Player
First thing to do on your player is to add a RigidBody2D. A RigidBody is the component Unity uses to check if a given GameObject is part of the Physics System, i.e. has gravity enabled and/or has collisions to be checked.
But there is a slight trick: Collisions are not exactly handled by the RigidBody but by another component, the aptly named Collider!
Go back to your Player GameObject and add a new BoxCollider2D component. You can play on the offset and size to better fit your sprite.
After adding these components to your player, you’re done with it! Now, it’s on to the Tilemap.
On your Tilemap
When creating a 2D level using grids/tilemaps, it is important to seperate what you paint into layers and not do it all on the same tilemap for several reasons:
Easier to Navigate in the Editor
You can play on the sorting order
Solid layers can be set appropriately
So how do we turn our ground solid? Well, it’s simple. Select the appropriate Tilemap (in our demo, this is the SolidTerrain GameObject), Click on “Add Component” and select “TilemapCollider2D”.
And now… you’re done! Seriously, that’s all! The TilemapCollider2D does the heavy lifting of computing collisions etc for our tilemap, no matter its shape so that we don’t have to.
Freeze Rotation
As is tradition, there’s actually one last thing to check. If you play around at this point, you’ll realize something: when the player collides with the ground, it actually starts to rotate!
This is actually to be expected since we are dealing with rigidbodies. Thankfully the fix is, once again, very simple: go to your player’s RigidBody component and, in constraints, tick the Z box for FreezeRotation.