In this blog we will trigger an action with the collision of two colliders 2D in Unity. It is just an example and there can be many ways to do this.
1. What is a collider?
According to the Unity manual a “Collider components define the shape of an object for the purposes of physical collisions” which mean that is a define area in which the physics will work of any object. There can be multiple ways to trigger actions with colliders including when two objects come into contact or when two objects go out of contact.
In this example we will trigger an action when two objects come into contact.
This post require to use a script to move a gameobject, you can find it in in the blog “Move A 2d Object In Unity”
2. Create two objects to make a collision
Create two objects with the specifications of the image above, both with the Rigidbody2D component.
3. Add the component Collider2D to the gameobjects
Follow the indications in the image above, as you can see both are Box Collider 2D.
According to Unity manual “A collider configured as a Trigger (using the Is Trigger property) does not behave as a solid object and will simply allow other colliders to pass through. When a collider enters its space, a trigger will call the OnTriggerEnter function on the trigger object’s scripts.”
With this definition in mind we move on to the next step, the creation of the script that allows triggering actions on contact between the two objects.
4. Create the script
In the image above you can find the script to activate one or more actions between the two objects:
One object will go to the right with the collision and will be destroyed in 3 seconds
The other object will go move up with the contact
5. Set gameobjects in Unity
In the image above you can find how to set the game objects in the Unity editor.
6. Let’s see the result
If you make the things right, like the above images, enter in the playmode and make the two objects to collide, you will find the actions trigger when they collide.
And don’t forget to check out the rest of the blogs!!