r/UnityHelp • • Aug 11 '22

Need help with a box collider issue.

I am new to unity and I'm trying to make a runner game. At first I used a normal cube as my player and the box collider worked perfectly fine. But when I imported a player asset online I began having issues with the box collider.

This is a part of my code:

void Update()

{

if(Input.GetKeyDown(KeyCode.Space) && onGround == true && gameManager.gameIsActive == true)
        {
playerRb.AddForce(Vector3.up * jumpForce * Time.deltaTime, ForceMode.Impulse );
playerAnim.SetTrigger("Jump");
onGround = false;
        }

}

private void OnCollisionEnter(Collision other)
    {

if(other.gameObject.CompareTag("Ground"))
        {
onGround = true;
        }
    }

The problem is that the onGround bool is always set to false even when my player is on the ground. I tried resizing the box collider and I tried using a mesh collider but nothing worked. Any idea of how to fix this?

2 Upvotes

5 comments sorted by

1

u/MischiefMayhemGames Aug 11 '22

Well I do not have a for sure answer as to what it might be. But I can suggest a few things you can try.

Sometimes importing stuff can screw up tags. So check to make sure the tags are still what they are supposed to be.

You can try adding some debug calls to check to see if the collision is actually occurring, this won't actually solve the problem, but it might help narrow down the cause.

Similarly a collision involves two parties. So it might be an issue with the floor object instead of the player. Again might not be the problem but helps eliminate possible causes.

The script looks like it should work so it does suggest some kind of issue with the collider parameters themselves.

1

u/Lara372007 Aug 12 '22

I tried many ways but the only thing that worked was when I removed the on Ground bool from the jump if statement. But thanks a lot for the help!

1

u/MischiefMayhemGames Aug 13 '22

That suggests something is causing that to trigger when it should not be. Maybe a stuck key? Although looking at this again another thought occurs to me.

You might try moving the physics logic into FixedUpdate. Keep the input login in update, though.

It would look something like this

bool jumpKeyPressed = false;
void Update()
{
    jumpKeyPressed = Input.GetKeyDown(KeyCode.Space);

}


void FixedUpdate()
{

     if(jumpKeyPressed && onGround == true && gameManager.gameIsActive == true)
        {

         playerRb.AddForce(Vector3.up * jumpForce * Time.deltaTime, ForceMode.Impulse );
         playerAnim.SetTrigger("Jump");
         onGround = false;
        }
}

1

u/Lara372007 Aug 13 '22

I've tried this out and it worked. Thank you very much for your help!

1

u/MischiefMayhemGames Aug 13 '22

Glad I could be of help (if a bit delayed).