Collision Detection and Physics

Katie Jeffree
3 min readApr 10, 2019

--

One of the most exciting parts of creating the platformer is creating the movement of the player itself. However, before I can start working on the movement, I need to set up two important aspects of the player’s physics. The first, most important part of this process is to make sure the player can collide with the platforms and the ground, otherwise it would fall right through into nothingness. The second important part is to add some aspects of physics to the player so that it can be affected by gravity. If the player did not have gravity added to them, then they would just float in the air after they jump, instead of landing on the ground. In Unity, you can add components to an object in the game. These are premade scripts or scripts written by the developer, which contain code that adds functionality to an object. One of these premade components is RigidBody2D. This component adds some rules of physics to an element (for example, giving it mass so that it is affected by gravity, specifying which direction the object can move, and allowing it to rotate). I added RigidBody2D to the player’s sprite so that it would fall down the screen until it reaches the ground. However, as the player object has no way to tell if it has reached the ground, it currently falls straight through, and continues to fall offscreen. This is not ideal.

To help the player identify when it has reached the ground, I had to add some collision detection to both the player and the ground objects. This ensures that when the player object and the ground object collide (i.e. when one object hits the other), the player stops moving. To achieve this, I added two collider components to my objects, a PolygonCollider2D to the player object and a BoxCollider2D to the tiles. The box collider provides a colliding radius to an object in the shape of a square. This was perfect for the ground objects as they were also squares, so the collider would fit perfectly around the edge of the tile. As the player’s shape is not a basic shape (e.g. a square, circle or triangle), I needed to use a collider that could be altered into any shape, to get the collision area as close to the area of the player as possible. The Polygon Collider fills this need as it is a lot more flexible with its edges and shape. This allowed me to bring the edges of the collider closer to the edges of the player image. The green line around the image of the player sprite below is the shape of the collider. It’s not perfect, but it will work for my needs.

PolygonCollider2D altered shape for my player’s sprite

Great! Now my player lands on the ground, I can begin working on its movement! See the gravity and colliders in action:

Player sprite landing on the ground after adding collision detection and physics

--

--