Game development is not as hard as it sounds. But it sure requires a lot of effort and good teamwork. Creating a real-world game means taking care of many parameters such as gravity, materials e.g bounciness, metalness, etc. There’s speed, power, drag, and collision. Collison is one of the most important criteria in the development of any game.
How to Detect Collision in Unity. In a natural environment, things collide with each other affecting each other differently. For example, if a fast-moving car strikes with another car the effect is very different from when a stuffed toy falls and collides with the ground.
In games, we need to detect when two different objects collide. The timing of the collision can trigger the next event For Example, if a bullet strikes with the enemy, we need to detect that to increase the score of the player. The precision of the detection is important.
Now in unity, you can do it through detection of the collision. You have to add a rigid body to one of the colliding bodies and colliders to both game objects. Using OnTriggerEnter() and OnColliderEnter, on both bodies.
OnTriggerEnter – Is called whenever an object with a collider has passed through an object with an “isTrigger” checked collider. For example, if you were to make a box trigger and the player walked through it, that would fire the OnTriggerEnter method on that object.
OnCollisionEnter – Is called whenever an object with a collider has collided with another object that contains a collider. For example, if two cars were to crash into one another, that would fire the OnCollisionEnter method on both of those objects.
How to Detect Collision in Unity | 3D Game Development
1. Add collider to the surfaces that are supposed to collide.
2. We added box collider to the grave, also since we are gonna use OnTriggerEnter() we will check istrigger. Resize the box collider according to the shape of the grave.
3. Add a rigid body to one of the surfaces. We added a rigid body to the sphere.
4. To the axe, we added a sphere, unchecked mesh and added a sphere collider, also check istrigger here.
5. Attach a script to one of the colliding objects. This simple code will detect the object with the tag sphere and will detect the collision and upon detection, it will play the animation
This is it for today’s tech-recipe.
Check out these Tech-Recipes