Introduction to Physics in Unity
Day 6 — Aspiring Game Creator
2D Game Dev: Galaxy Shooter
Unity’s physics engine, whether 2D or 3D, gives game objects the convincing behavior needed to feel or look as if:
- A plane has crashed into the ocean and is beginning to sink.
- A hand grenade has exploded next to a crate of dynamite setting off a change of explosions, destroying a building in its wake and slowly the building creaks and tips and crashes down.
- A fleeing car has perfectly drifted around a crazy hairpin corner while the police cars in pursuit drive head on into a charming French bistro.
- An enemy spaceship has warped in from nowhere, banks around an asteroid, fires its afterburners and twists and turns, firing its laser cannons, targeting the player for a straight on collision.
These physics simulations: collisions, mass and acceleration and how they interact with other objects and gravity are all handled by Unity’s Physics Engine.
One important note about Unity’s physics is there are two systems: 2D & 3D and though they generally behave and have similar components and attributes and methods, the two systems DO NOT interact with one another.
The physics engine is extremely complex, but in terms of Galaxy Shooter 2D, this article will focus on a few key components.
The rigidbody component is what a game object needs to begin to use the Unity Physics engine.
The rigidbody component works in conjunction with colliders to detect collisions.
Finally collisions come in two forms, a hard collider and a trigger collider. A hard collider physically interacts with opposing forces — two trains colliding head on — while a trigger only detects if the collider has interaction with another.
Above the enemy invader game object has both the rigidbody and collider. Because the enemy’s movement will be driven by code and shouldn’t respond to gravity or physical collisions, its rigidbody is set to: Is Kinematic.
The collider is set to: Is Trigger, also bypassing the physics engine and only reporting when the game object’s collider has interacted with another.
Whenever any other game object collides with the enemy invader it will be treated as a GAME EVENT rather than a physical collision.
When the spaceship fires its laser cannons, the set of projectiles fire upward. These two game objects have colliders.
Upon impact, the enemy collider reports that a collision has been triggered. The Event.
Upon collision everything about the colliding game object is available.
The code examines the collider’s game tag and if that tag equals “Laser” the enemy instantiates an exploding copy of itself, disables its own mesh and destroys itself two seconds later.