Monday, 14 December 2015

Collision Detection and Handling in Unity

Collision detection in Unity at its simplest can be explained by two objects in Unity having invisible boxes around them called 'hitboxes', and when these two objects collide (by having the two triggers overlap) they can set off some code to run. This can have a variety of uses from having a player die when they run into an enemy, to picking up and grabbing -in-game collectables. As posted by (clunk47, 2015) from Unity Answers, there are multiple ways to handle collision in C# code, such as using OnCollisionEnter or OnTriggerEnter where you can then identify what will happen, such as this code from (animationanalyst, 2015), which simply destroys the main character
game object when a bullet (a game object that contains the tag of 'bullet') collides with them (which is very well optimised due to only being a few lines long): "

  1. void OnTriggerEnter(Collider other)
  2. {
  3. if(other.gameObject.tag=="bullet")
  4. Destroy(gameObject);
  5. }
"

Using the Unity editor, you can apply Box Colliders (for 2d or 3d games) right in the inspector view, and then scale/ adjust the size and placement accordingly to match the object's general shape. You can normally only have one box trigger at a time, by adding it as a component for the character, so instead making the main character a parent class, then creating various other blank game objects underneath it with their own box triggers can create a much more intricate form of collision detection and not have the character have a simple box around them with dodgy collision from certain angles. Here's an example image (screencapped by me) for a main character below (the green boxes represent various box colliders attached to one object, which help shape the general dimensions of the bird and how a simple box wouldn't be able to properly fill the whole shape):

Raytracing is a more advanced version of collision detection that doesn't use boxes, but draws invisible lines instead, which I explained in more detail in an earlier blog post!

No comments:

Post a Comment