I am making a pacman game, and when the ghosts move around, they hit a trigger box, and get a random number from there. I have the ghost make a random number when it is OnTriggerStay(). The problem is, sometimes the ghost detects that there is a trigger earlier or later rather than right in the middle of the trigger. As a result, the ghost will ram into the walls and get stuck. How can you make the OnTriggerStay only execute when it is in the middle of the trigger?
I’m not sure if I understand your problem.
OnTriggerStay will be executed every frame as long as the colliders (triggers) intersect.
I can think of two ways to work around what you need.
One would be to calculate the distance between the trigger center and the ghost. If it’s bigger than a value you specify, then ignore the OnTriggerStay.
Another is to make the trigger smaller, in order to only work when you need it to work.
Here is a file of my game (please don’t mock me for the horrible code). If you play it, you will see the red ghost bump into the wall, and stay there. If you can find a solution that would perminatly eliminate this, I would be very thankful.(I don’t know if the download will work…)
If you are wanting it to only happen 1 time, a smaller collider and using OnTriggerEnter may work just as well. It’s only called once and won’t call again until after the colliders are no longer intersecting, and then re-intersect.
This could work for a larger collider as well, but saying smaller so you can control the exact spot you want it to trigger.