Physics in Unity: An introduction (Game Dev Day 10)

Jack Leavey
2 min readJul 22, 2021

--

Physics inside of a game environment is referring to how objects interact with each other or outside forces. One of the easiest concepts to grasp is gravity; the object with gravity applied to it will fall down. So how can we use physics to create our 2D space shooter?

What are the physics in play to makes these interactions work?

Lets look at our enemy prefab (the red blocks) and see what makes them interact with our lasers.

The code for our enemy to interact with the other objects.

Using if/then commands, we can set the enemy to interact with both our Player and our Laser prefabs. The first command tells the enemy to “damage” the player by removing a variable called Lives from the player, then to destroy itself.

The second command tells states that if a laser and an enemy collide, then the laser is destroyed followed by the enemy.

Now the code here is correct but if we input this as is nothing is going to happen. That’s because unity requires the objects to have colliders to read collisions. At least one of the objects in the collision MUST have a collider attached.

For now, we will utilize box colliders as our game is set up in a 3D environment.

We will put box colliders on our player, enemy, and our lasers. Box colliders are sometimes referred to as “hitboxes” as well. We can edit the area that is considered a “hit” by clicking the “Edit Collider” option at the top of the Box Collider tab.

We will also be adding rigid bodies to ensure that physics that we want are applied to the object. For our game, we are going to turn gravity OFF as we do not want our spaceships falling off the screen into oblivion.

We will be unchecking Gravity to ensure our spaceships actually float in our space scene.

With these parameters in place, we can shoot our enemies and be destroyed if we collide with them!

--

--

Jack Leavey
Jack Leavey

Written by Jack Leavey

I am a software engineer with years of experience branching into game development, specifically in Unity. Follow along for guides on creating game mechanics!

No responses yet