- Home /
Advice for Detecting Intersections With Object Being Placed
I'm working on a tower defense game and rather than limiting the player to only placing towers on specific, predefined spots, I want to let him place them anywhere on the ground that is open. However, towers should not intersect each other or other world objects such as buildings or walls.
I'm wondering what the best way to implement this would be. I have a script on my camera that does a ray cast every frame to get the point on the terrain under the cursor, that's simple enough. Now I want to know if the selected tower type will fit there, or if there is another obstacle nearby.
Should I attach a script to the tower that's being placed on the ground, and in that script have an OnCollisionEnter() callback that simply tells the camera that the tower has collided with something and can't be placed there? Or is there a way I can do a "cube cast", kind of like how I can do a Physics.Raycast or Physics.SphereCast and handle the collision detection in the same script on the camera that I check for the ground point under the cursor?
Answer by KrisCadle · Jan 23, 2012 at 12:54 AM
then use the collider on your prefab to disable placement ability and activate your red outline... you can have any function you want with a trigger on your prefab - plus adjust the size of the collider so it gives you the right buffer zone etc...
function OnTriggerEnter (other : Collider) {
Destroy(other.gameObject);
//or whatever else you want to do
}
Answer by KrisCadle · Jan 22, 2012 at 10:54 PM
if your prefab has a collider then maybe you could just have it destroy itself if it is touching anything like a building or tree etc (use tags)... It would look like nothing happened but you can instantiate a GUI label (for a couple seconds) that says "try again" etc...
That way you could only place a tower when it is not touching anything else. Also the only code you have would be running on your prefab and not running in your update on your camera...
Hey $$anonymous$$ris, thanks for the suggestion. I don't want to destroy the object if it intersects something else, just highlight it red or something to show that it can't be placed there. The object will follow the mouse cursor until it is placed in a valid position, or the user hits Escape to cancel placing it.
Your answer
![](https://koobas.hobune.stream/wayback/20220613063256im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Using Trigonometry for Collision Detection 0 Answers
Problem in spherecast . 1 Answer
Test If Two Colliders Overlap 0 Answers
Prevent explosion through walls 0 Answers
How many ways to stop player from going through walls? 1 Answer