Introduction
This article demonstrates the basics of Collision detection and how to create physical materials and triggers in Unity.
Prerequisites
Unity Environment version 5.6.1
Create Terrain
Step 1
First, you have to open the Unity project. Click on the GameObject in the menu bar. Select 3D object and pick the Terrain.
Click on the Cube in the lft menu. Go to "Add Component" and select the physics option. Then, click on the Rigid body, as shown below.
Do the same with blue cube also.
Go to the Rigid body and uncheck the "Use gravity" option.
Click on the “Play” button. The cube will fall down.
Click on the cube1. Go to the Inspector panel. Select the constraints and check all X, Y, Z boxes.
Click on the “Play” button. The cube will fall down to the position.
Collision basics
Step 3
Click on the cube. Go to the "Add component" and select the "Sphere collider".
Go to the Box collider >> corner icon. Select the "Remove component" option.
Click on the “Play” button. The cube can be falling down and moving out to cube1.
Create Physic material
Step 4
Click on the Assets menu in the menu bar. Select the create and pick the Physical material option.
The physical material is added in to the assets. Rename as bouncy. Go to the sphere collider click on the material option select bouncy material.
Click on the bouncy material. Set 1 as bounciness. Set the maximum for bounce.
Click on the play button. The cube can be bounced into the terrain.
Triggers in unity
Step 5
Click on the cube1. Go to the box collider Check the trigger box.
Click on the “Play” button. The cube will be entered into cube1.
Go to the mono development in unity and write the coding like the following.
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- public class NewBehaviourScript: MonoBehaviour {
- void OnTriggerEnter(Collider other) {
- print("Another object has entered the trigger");
- }
-
- void Start() {}
-
- void Update() {}
- }
Save the program.
Come back to the Unity window. Click on the “Play” button. The cube will enter cube1, and “Another object has entered the trigger” message will be displayed into the console panel.
Go to the mono development in Unity and write the code like the following.
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- public class trigger: MonoBehaviour {
- void OnTriggerEnter(Collider cube) {
- Destroy(cube.gameObject);
- }
-
- void Start() {}
Save the program.
Come back to the Unity window. Click on the “Play” button. The cube will be destroyed when it enters the cube1.
Summary
I hope you understood collision detection basics now.