How do I create separate colliders on an object?

I am currently creating a side scrolling game where a player can jump if its contact with the ground. In the code I simply have a variable in which holds a boolean value of whether or not the box collider on the character in colliding with the ground. But the issue with this is the character can simply climb up the sides of walls because it still is technically colliding with the ground. I had an idea of having a separate collider on the object where is would be only on the bottom so that i would be able to find whether or not the bottom of the collider was touching the floor but there can only be one collider on an object at a time. I was wondering how i should approach this issue because i am clueless as to how to go about this.

1 Answer

1

The simple way is to add a child GameObject and attach the collider to that. Then you just have to wire the two objects together in code.

The more complex way is to check the Normal Vector coming from the colliding object.
Here is a simple script to do that.

GameObject groundedOn = null;
bool isGrounded = false;
 
function Update(){
  if(isGrounded)
  {
    //do something
  }
}
 
function OnCollisionEnter(theCollision : Collision){
  if(theCollision.gameObject.rigidBody.isKinematic) //Only want kinematic rigidbodies
  {
    foreach(ContactPoint2D contact in theCollision.contacts)
    {
      if(contact.normal.y > someThreshold)
      {
        isGrounded = true;
        groundedOn = theCollision.gameObject;
        break;
      }
    }
  }
}
 
function OnCollisionExit(theCollision : Collision){
  if(theCollision.gameObject == groundedOn)
  {
    groundedOn = null;
    isGrounded = false;
  }
}

Which way did you go?

Thanks for the answer! Just another question though, on line 16 you write "if(contact.normal.y > someThreshold)"... Im a little confused on why contact.normal.y isnt a boolean? Rather is seems like its a double...

I decided to utilize the contact.normal route because it seemed more efficient and direct.

contact.normal represents the direction of the force applied by the other object. If the normal points up, like in contact with the floor, then your character is grounded. If the normal doesn't point up, then you character is hitting a wall, or ceiling, etc..., and is not grounded. normal is also a unit vector, meaning X^2 + Y^2 + Z^2 = 1. So, you can check how far up it is pointing just from examining Y. If Y is above someThreshold, then the normal is sufficiently Up enough for your character to be grounded.

If Y == 1, then the normal is completely vertical. But, comparing doubles for equality is a bad idea. What you really want is to check if it is close to 1. You will have to determine how close, because it depends on each individual project. Start with something like Y == .9d and go from there. If it is too sensitive, increase it. If it is not sensitive enough, decrease it.