blueeyesdragon
blueeyesdragon

Reputation: 1

OnCollisionEnter Does Not Work

I am making a crouching script in my unity game. One problem I had was when you uncrouch and you are under something you still go up and you get stuck. The solution was to create a child of the player that checks if there is anything above the players head

the code would work something like this

void OnCollisionEnter(Collision collision)
{
    isunder = true;
     print("collide")
}
void OnCollisionExit(Collision collision)
{
    isunder = false
}

for some reason, I cannot get it to work. everything has a collider, everything has a rigidbody, everything has been kinematic and not kinematic. I just don

Upvotes: 0

Views: 395

Answers (1)

Andy Riedlinger
Andy Riedlinger

Reputation: 311

So I am not quite sure how you are trying to set up your scene, but using Collision to check if an object is above your head isn't really possible as if you are using an empty gameObject with a rigidbody, it won't detect anything, and if you put a collider on it, you now have an invisible object running into stuff. So I suggest you use Raycasting or Triggers

To use a trigger put a collider on your gameObject, and set isTrigger to true. Then in your code you can use these:

void OnTriggerExit(Collider collision)
{

    Debug.Log("Exit");
}
void OnTriggerEnter(Collider collision)
{
    Debug.Log("Enter");
}

Works just like collisions except it is an invisible field that will not cause any actual collision.

The other way, raycasting, could also be used.

public Transform rayStart;
float length; //Set equal to how far above head you want to check
public bool underObject() {
    return Physics.Raycast(rayStart.position, Vector3.up, length);
}

Just make sure the gameObject that is your rayStart, probably at the top of your characters head, is not inside your character, or the ray will hit your character and always return true. Length would probably be the difference in distance from crouching to standing.

Upvotes: 2

Related Questions