0
\$\begingroup\$

I'm trying to detext when player goes inside and exit this house.

enter image description here

As the picture shows I need two colliders because the house is not an exact rectangle.

So I added two box colliders to an empty gameObject with a proxy trigger.

enter image description here

The problem is that the trigger exit is being called when player goes from one collider to the other one. What I want is that both works as "single collider".

Is that the correct way to do it?

\$\endgroup\$

2 Answers 2

3
\$\begingroup\$

If there's only one thing (the player) these triggers interact with, you can do something like this:

public class CompoundTrigger : MonoBehaviour {

    public UnityEvent OnFirstEntrance;
    public UnityEvent OnLastExit;

    int _activeOverlaps;

    void OnTriggerEnter(Collider other) {
        if (++_activeOverlaps == 1)
            OnFirstEntrance?.Invoke();
    }

    void OnTriggerExit(Collider other) {
        if (--_activeOverlaps == 0)
            OnLastExit?.Invoke();
    }
}

This maintains a count of how many collider pairs are overlapping. It fires its events only when that count changes from 0 to 1 or from 1 to 0.

When the front tip of the player object enters the collider for the second part of the house, it increments the counter from 1 to 2, so no event fires.

Then the last bit of the player object exits the collider for the first part of the house, decrementing the counter from 2 to 1: again, no event fires.

This works as long as the player can't fully exit the first part of the house before they enter the second (no gaps between them, and no teleporters). You can even overlap the two colliders to give some margin of error here in case of a fast-moving player crossing the threshold in a single time step.

Only when all colliders have been exited will OnLastExit fire.

If you need to maintain this for more than one entity (e.g. multiple players), then you'll need to store a map with a separate counter for each colliding agent, but the general principle stays the same.

\$\endgroup\$
0
0
\$\begingroup\$

You can add a polygon collider. That is a bit difficukt to set up, but it would nerge the two box colliders into one.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ A PolygonCollider is for 2D physics, not 3D. In 3D you have a MeshCollider, but for non-convex shapes it only represents the skin of the surface, and does not detect overlaps in the interior. \$\endgroup\$
    – DMGregory
    Commented Apr 8 at 10:42

You must log in to answer this question.

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