Introduction to Physics in Unity
Interaction Between Objects
So, I have more than one object in my game and I need to make them interact with each other in different ways. What do I do?
My 2D Space Shooter example will do just fine to explain the basics of physics in Unity.
To give any type of physics to a gameObject, you have to add a Rigidbody component to that gameObject.
- To add a “Rigidbody” component to a gameObject, you click on the GameObject inside the “Prefabs” folder within the Projects panel and click on the “Add Component” button at the bottom of the Inspector panel.
- Begin to type Rigidbody into the search bar. Click on “Rigidbody” in the list and uncheck the “Use Gravity” option so the gameObject doesn’t just drop to the bottom of the screen.
Now you can see that a Rigidbody component is now attached to the gameObject.
Now, add a Rigidbody component to the gameObject that will interact with the one to which we already added a Rigidbody component. In my case, I added a Rigidbody to my Enemy prefab and one to my Laser prefab. Be sure to uncheck the “Use Gravity” option on this one also.
Adding Code to Make our gameObjects Interact
Now we have to add some code to a couple of our C# scripts.
- First, I’ll add an OnTriggerEnter() method in my “Enemy” script.
private void OnTriggerEnter(Collider other)
{
if (other.tag == “Player”)
{
Player player = other.transform.GetComponent<Player>();
if (player != null)
{
player.Damage();
}
Destroy(this.gameObject);
}if (other.tag == “Laser”)
{
Destroy(other.gameObject);
Destroy(this.gameObject);
}
}
This code says, if I (Enemy) Collide with an object labeled by tag “Player”, and player is not null, then run the Damage() method on the “Player” script and Destroy me (Enemy). If I (Enemy) Collide with an object labeled by tag “Laser”, then Destroy object “Laser” and Destroy me (Enemy).Note: OnTrigger type collisions are pass through collisions and OnCollision type collisions are hard surface collisions. An example of an OnTrigger collision would be picking up a powerup or coin. An example of an OnCollision collision would be like the player smashing into a wall.
- Now, in the “Player” script, I add the following code.
public void Damage()
{
_lives --;if (_lives < 1)
{
Destroy(this.gameObject);
}
}
When the Damage() method is called, 1 is subtracted from the current value of the variable _lives. If the value of _lives becomes less than 1, then Destroy me (Player).
So, using the Rigidbody component and OnTriggerEnter, along with some added code in your scripts, you can see how we now have basic physics. When one object hits another, something happens based on the what the script wants to happen.
Please Like, Share, and Follow.