- Home /
 
What's wrong with OnCollisionEnter?
I have this script attached to the player, but when he touches a cube(with the tag up or down) nothing happens. Why?
 var speed : float;
 
 var touchingUp : boolean;
 var touchingDown : boolean;
 
 function Update () {
     if(Input.GetButton("up") && !touchingUp)
     {
         transform.Translate(0, 2 * Time.deltaTime, 0);
     }
 
     if(Input.GetButton("down") && !touchingDown)
     {
         transform.Translate(0, -2 * Time.deltaTime, 0);
     }
 
 }
 
 function OnCollisionEnter (other : Collision) {
     if (other.tag == "up") {
         touchingUp = true;
     }
         if (other.tag == "down") {
         touchingDown = true;
     }
 }
 
 function OnCollisionExit (other : Collision) {
     if (other.tag == "up") {
         touchingUp = false;
     }
         if (other.tag == "down") {
         touchingDown = false;
     }
 }
 
              Answer by Seth-Bergman · Dec 28, 2012 at 10:23 PM
there are several possibilities:
1: the tag is not actually set on the object
2: more likely, one of your objects needs to have a RIGIDBODY attached. For a better idea of exactly which object combinations will send collision messages, look here:
http://docs.unity3d.com/Documentation/Components/class-BoxCollider.html
the collision matrix at the bottom is very helpful for understanding this
3: obviously, both objects must have a collider, NOT SET to "isTrigger"
here is another helpful link on the subject:
Answer by aldonaletto · Dec 28, 2012 at 10:38 PM
The player must have a rigidbody attached in order to generate OnCollision events. If it's a simple object (no Rigidbody, no CharacterController), add a Rigidbody to it and change the control code a little:
 function Update () {
     var speed = 0;
     if (Input.GetButton("up") && !touchingUp)
     {
        speed = 2;
     }
     else
     if (Input.GetButton("down") && !touchingDown)
     {
        speed = -2;
     }
     rigidbody.velocity = Vector3(0, speed, 0);
 }
 
               Another possibility is to add a CharacterController instead of the Rigidbody - you would not even need the OnCollision events to make it be constrained by the up and down objects: a CharacterController doesn't go through other colliders when you move it with Move, like this:
 function Update () {
     var speed = 0;
     if (Input.GetButton("up"))
     {
        speed = 2 * Time.deltaTime;
     }
     else
     if (Input.GetButton("down"))
     {
        speed = -2 * Time.deltaTime;
     }
     GetComponent(CharacterController).Move(Vector3(0, speed, 0));
 }
 
               NOTE: If using a CharacterController, OnCollision events aren't generated - you should use OnControllerColliderHit instead.
Thanks, but if I use a character controller, it applies gravity to the object
No, you must add the gravity in your script when using $$anonymous$$ove - only Simple$$anonymous$$ove includes gravity automatically.
Your answer