I would like to be able to tell when one object is trying to exit the collider of another and possibly block the motion that would cause the exit.
I have a system in which objects are sometimes able to be physically interacted with (stood on, bumped into, etc.) and sometimes not (when not, they can still be interacted with via other code, but not by physics), so the isTrigger property of some objects changes dynamically. My problem is actually that colliders sometimes do a isTrigger = false
while a rigidbody is inside them which causes bugs. Generally, what causes other nearby objects to change state is entering/exiting a separate object.
So basically, entering object 1 causes objects 2 through N to change, like so…
void OnTriggerEnter2D(Collider2D other)
{
foreach(GameObject o in specialInteractionItems)
o.GetComponent<BoxCollider2D>().isTrigger = true;
}
void OnTriggerExit2D(Collider2D other)
{
foreach(GameObject o in specialInteractionItems)
o.GetComponent<BoxCollider2D>().isTrigger = false;
}
Some of these “special interaction items” are inside the collider of this
, some of them are outside, and some of them overlap (part in, part out). If OnTriggerExit2D() is called while the player is currently overlapping (or even entirely within) a specialInteractionItem when that item gets isTrigger = true
, that is the problem, as I then have my player (with its rigidbody) inside some other object which it normally cannot move into - the physics would normally have been disallowing this if not for the special interaction state.
It would be wonderful if Unity had some kind of bool OnAttemptedEnter()
and bool OnAttemptedExit()
which would disallow the translation if false is returned. If this exists, I want to disallow the above-mentioned exit, forcing the player to remain in a state where it is colliding with the other object. I have used other development environments which have this, and it is very useful. Does Unity have anything like this?
If Unity does not have this built in, I think I need to set up such a thing myself, but I would not know where to start doing this in Unity. Google was not much help, as it found plenty of results which had nothing to do with this.
Does anyone know how to do this, or does anyone have any recommendations or other ideas?