Physics in Unity: An introduction (Game Dev Day 10)
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?
Lets look at our enemy prefab (the red blocks) and see what makes them interact with our lasers.
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.
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.
With these parameters in place, we can shoot our enemies and be destroyed if we collide with them!