Saturday, November 9, 2013

Collision detection with Unity3D

So by now I know how to do animation and object creation in Unity3D. Now I started to learn how to get collision detection working with Unity3D.

In Unity3D collision is detected by using various collider objects. Box collider should work for most 2D games. There are some other shapes collider also available, but that I am not going to discuss here.

So to start, I created a basic setup, one egg and one cube which will act as wall and all I want it notification when egg collides the wall.



Now we have scene setup, so for egg to be able to detect collision, go to Box Collider in inspector, and select Is Trigger option. By selecting Is Trigger, egg can move through wall but still gives us notification of collision. In this post I am going to work with Trigger only.



For collision detection to work in Unity3D, atlest one of object needs to be rigid body. so lets add rigid body to egg.



Now we are ready, lets add script which makes egg move. script looks like below.
using UnityEngine;
using System.Collections;

public class Movement : MonoBehaviour {
 
 private int frame;
 
 // Use this for initialization
 void Start () {
  frame = 0;
 }
 
 // Update is called once per frame
 void Update () {
 
  //skipping some frame to make animation look smooth
  if( Time.frameCount % 10 != 0 ) {
   return;
  }
  
  //makeing it move
  transform.position += new Vector3((-5.0f * Time.deltaTime), 0.0f, 0.0f);
  
  //sprite animation
  frame++;
  if( frame > 8 ) {
   frame = 0;
  }
  renderer.material.mainTextureOffset = new Vector2(frame*0.125f,0);
 }
 
}
Now if you run the game, you can see egg moving but to be able to detect collision we need to add following functions to the script.
 
        void OnTriggerEnter(Collider other)
 { 
  Debug.Log("Collision enterd:" + other.gameObject.name );
 }
  
 void OnTriggerExit(Collider other)
 {
  Debug.Log("Collision exited:" + other.gameObject.name );
 }

Now if you run the game, you can see logs printed when egg pass through wall. Here is how it works.

We can also detect collision with empty game object as well.Just add empty game object to scene and add Box Collider to it. That's It should work just the same.

 

No comments:

Post a Comment