- Home /
Solved: How to know if an object collides with anything at all? (Jumping issue)
This is a pretty simple jumping script,
void onUpdate() {
if (Input.GetButtonDown("Jump") && onGround)
rigidbody.velocity += new Vector3(0, jumpVelocity/50, 0);
}
void OnCollisionStay(Collision collision) {
foreach (ContactPoint contact in collision.contacts)
if (Vector3.Angle(contact.normal, Vector3.up) < maxSlope)
onGround = true;
}
void OnCollisionExit (Collision collision) {
onGround = false;
}
but you see the problem is that when the object (let's say floor) gets destroyed and there are no other colliders, OnCollisionExit is not triggered and OnCollisionStay also stops functioning. In which case my player can still jump infinitely many times until I hit a floor.
I wonder if there is maybe a way to know if a player does or does not collide with anything at all. That would solve my problem.
You'd do that simply by saying
void OnCollisionEnter(Collision collision){
//check whatever boolean variable true
}
This is checking your hit or whatever variable true upon any collision.
I thought of a better way which let me know if OnCollisionStay() happens or not, in other words I would know if any collision is happening and check if collision is correct for me. But I forgot to mention couple very important lines
if (onGround)
rigidbody.useGravity = false;
else rigidbody.useGravity = true;
This gravity adjusting code (if player is on the ground or not) makes stuff very glitchy especially when ground actually disappears. It makes sense to always apply gravity, even when object is standing on something solid (I just followed ETesskiTutorials)
I thought what you wanted was to do was prohibit movement when not on ground, but that code seems to do the opposite with gravity.
I see it. So you only want to adjust gravity? I thought gravity works that way on its own... Alright then.
Yes, but it doesn't work. Player just keep bumping up and down (slightly, but pretty irritating) It seems these lines of code just messed everything up. Because when gravity is off and collider is gone, it doesn't detect that it lost the collider, so onGround was left true and gravity left false, what made me float in the air and jump infinitely high. That seems to be the problem :P
(if it's questionable everything else works with the code, player jumps once and so on. In air gravity was activated since player actually left the collider by himself)
Answer by Hyperion · Aug 04, 2013 at 06:45 PM
But here's my code to check if you're on the ground or not, and it works:
void OnCollisionEnter(Collision hit){
if (hit.gameObject.tag=="terrain"){
grounded=true;
}
}
void OnCollisionExit(Collision hit){
if (hit.gameObject.tag=="terrain"){
grounded=false;
}
}
Hope this helped - Hyperion
This solution is for "when" via an event, not "if" via a test which is what the title asks.