Thursday, December 4, 2014

Unity: Collision Detection

Collision detection in Unity is extremely simple. For each game object that the player character will collide with, add a collider (e.g., by selecting Component->Physics->Box Collider), next enable the "Is Trigger" property in the game object's "Box Collider" section. We can set a tag to these game objects so that they can recognized by their tag, e.g. a tag like "enemy". Now in the MonoBehavior C# script attached to the player character, add the following method:

void OnTriggerEnter(Collider hitCollider)
{
 if("enemy" == hitCollider.tag)
 {
  GameObject enemy=hitCollider.gameObject;
  this.Treasures.Add(hitCollider.GetComponent<Treasure>());
  Destroy(enemy);
 }
}

The method above destroy any "enemy" the player character collides with and steal its Treasure item.

No comments:

Post a Comment