I am making a 2D tower defense game and am currently struggling with a problem with placing towers. Currently, I press a button to create a “phantom tower” which follows the mouse. I want to be able to click to place the tower, but I cannot figure out how to properly detect whether or not the tower is colliding with the road/water/obstacles. I have polygon colliders over the unplaceable areas of the map and a box collider on the phantom tower. I have an OnTriggerEnter which changes the placability to false and an OnTriggerExit which makes it placeable again. When I Debug.Log the placeability of the tower in update, it is inaccurate and wonky. When I Debug.Log in the collision detection, it gives the correct results. I need to be able to get the actual placeability in update so that I can detect the click to place the tower properly. I don’t know much about the execution order, update/fixedupdate/physics stuff, but I’m pretty sure this is the problem Does anyone have a solution to detect the collision in update?
It’s not clear what you actually do inside OnTriggerEnter / OnTriggerExit. Though if you have multple areas that are blocking the placement you get issues when your tower enters two of these regions at the same time. Because when you just use a single boolean value to remember the placability state you get a wrong value when you leave one of the two areas but you’re still inside the other. You would need to remember the state for each individual collider
This is generally a tricky problem. There are several solutions. If your tower has a rectangular or circular base you probably just want to use Physics2D.OverlapBoxNonAlloc or Physics2D.OverlapCircleNonAlloc otherwise Physics2D.OverlapCollider inside Update should work. So you can iterate through all colliders that currently overlap with your tower and detemine if it overlaps with a certain collider.
The other solution is similar but you would use OnTriggerStay instead of OnTriggerEnter / Exit. At the end of each frame you would reset the placability flag to true, With OnTriggerStay you would simply set it to false. This should give you the right placability state before you reset it back to true.
Though if possible I would highly recomment the first solution since you have more control over when the checks are carried out.
Turns out what I was doing actually worked just fine. The problem was that I had an if statement that overwrote it hidden away in a different part of the code for some reason.