I’m a making a basic 3D game using c# and I’ve got a basic movement done already but when it comes to jumping the player can jump in the air. I’ve made code so the player can only jump when touching the ground, but the Ground game object needs to be is trigger to work but when the player touches the ground the player falls straight through it.
Is it possible to have a box collider being is trigger and being solid?
If yes how do you do it?
The solution for my game was to start in the air and use
void OnCollisionEnter(Collision collisionInfo)
{
if (collisionInfo.gameObject.tag == "Ground" || collisionInfo.gameObject.tag == "Building" || collisionInfo.gameObject.tag == "Prop") {
canJump = true;
}
}
void OnCollisionExit(Collision collisionInfo)
{
if (collisionInfo.gameObject.tag == "Ground" || collisionInfo.gameObject.tag == "Building" || collisionInfo.gameObject.tag == "Prop") {
canJump = false;
}
}
}
It might be easier to check your player position (Y-axis). Using this, we can tell whether the player is grounded or not. This assumes that 0 is the position your player is at whilst grounded, if you have a raised floor then this might not be the case.
private bool IsGrounded => !(transform.position.y > 0);
private void JumpMethod()
{
if (!IsGrounded)
return;
// Do your jump method
}
This won’t work if you have different floor heights. If you want to go with the collision detection then you can use
private void OnCollisionEnter(Collision other)
{
if (!other.CompareTag("Player"); // Make sure player has tag
return;
// Player has hit the ground collider (solid)
}
private void OnTriggerEnter(Collider other)
{
if (!other.transform.CompareTag("Player"); // Make sure player has tag
return;
// Player has hit the ground collider (not solid)
}
But it doesn’t seem like you should have two colliders, one a trigger and one not. Could you not just have one collider (non-trigger) that checks that the player was the other collider, then set some value “IsGrounded” to true? Then you know the player has touched down, and you don’t have to worry about the player falling through the floor.
Like what “Casiell” said in the comments, a very simple way to do this is to add an additional box collider without IsTrigger. This will trigger the IsTrigger, and will let the player stay on the ground.