0
\$\begingroup\$

Currently trying to make a 2D game in Unity and I'm trying to make the part where if the character falls in a hole it goes back to spawn, but I currently have a ground box collider blocking it, which covers the entire floor. Can anyone help?

\$\endgroup\$
1
  • 2
    \$\begingroup\$ Presumably you considered making two colliders, one on either side of the hole, with a gap in between? Is there something that makes this unsuitable for your application? \$\endgroup\$
    – DMGregory
    Commented Jan 8 at 4:48

2 Answers 2

1
\$\begingroup\$

After looking around for the best solution, it seems that using the Layers in Unity is pretty awful when you want to code something with them. Best solution is to have an object with a trigger collider over your hole, and attach a script that listens to trigger collision to check if the player has collided with it; so when he does collide the script tells the physics engine to ignore all collision between that ground collider and the players collider.

The code looks something like this:

public class GroundHole : MonoBehaviour
{
    [SerializeField] private GameObject _ground;

    private void OnTriggerEnter(Collider col)
    {
        if (col.transform.CompareTag("Player"))
            Physics.IgnoreCollision(_ground.GetComponent<Collider>(), col, true);
    }

    private void OnTriggerExit(Collider col)
    {
        if (col.transform.CompareTag("Player"))
            Physics.IgnoreCollision(_ground.GetComponent<Collider>(), col, false);
    }
}
\$\endgroup\$
2
  • \$\begingroup\$ I'm curious what you mean by "using the Layers in Unity is pretty awful" - I've had very good experience coding physics interactions using layers. \$\endgroup\$
    – DMGregory
    Commented Jan 11 at 16:50
  • \$\begingroup\$ Because it's not very intuitive to use bitshifting; and because you can't set a layer mask for a specific object, you can only change the objects layer... It would be easier to just assign a layer mask to a rigidbody or collider. \$\endgroup\$
    – Džoni
    Commented Jan 11 at 16:55
0
\$\begingroup\$

You can add triger for example if player inside trigger you can remove player collider (or make player do not collide with the box collider layer) and it will falls. Or use 2 colliders as DMGregory said.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .