Sunday, December 2, 2012

Unity Detect Collision script

So let say you want to have something happen if collision detected, this is how you do it

1. Create a new script let say "collide"
2. Open your script , put

Function OnCollisionEnter()
{
    Debug.log("Collision detected");
}


However, let say you only want to do something if it collide with specific item

Function OnCollisionEnter( haha : Collision)
{
      if (haha.gameobject.name == "player")
      {
                  Debug.log("Collision detected on the player");
      }
      else if(haha.gameobject.name == "ball")
      {
                  Debug.log("Collision detected on the ball");
      }

}


then you just drag your script to your object that you wanna detect collision

However, this only work on Cube with rigid body

What if, you want the collision detect on your character controller and maybe you want to push the cube or ball around with your main character?

then below is the script that you should create and attach it to your main character



// this script pushes all rigidbodies that the character touches
var pushPower = 2.0;
function OnControllerColliderHit (hit : ControllerColliderHit) {
    var body : Rigidbody = hit.collider.attachedRigidbody;
    // no rigidbody
    if (body == null || body.isKinematic)
        return;
        
    // We dont want to push objects below us
    if (hit.moveDirection.y < -0.3
        return;
    
    // Calculate push direction from move direction, 
    // we only push objects to the sides never up and down
    var pushDir : Vector3 = Vector3 (hit.moveDirection.x, 0, hit.moveDirection.z);

    // If you know how fast your character is trying to move,
    // then you can also multiply the push velocity by that.
    
    // Apply the push
    body.velocity = pushDir * pushPower;
    
    if(hit.gameObject.name == "mycube")
    {
    Debug.Log("pushing cube");
    }
    else if(hit.gameObject.name== "myball")
    {
        Debug.Log("pushing ball");
    }
}

now my character can push the ball and cube around as you can see in the video




No comments:

Post a Comment