Grids / Array / Tower Defence...

Hi,

I had a look around in the previously posted questions but couldn't find an answer... (Sorry if there is one already :/).

Anyway, I have a terrain, and an orthographic view of it with my main cam. On a part of this terrain, I would like to create a Tower Defence game.

I am able to create an object on a mouse click using a raycast, but: This method allows to create 1000's of objects at the same location, while I would like one object only, and any further attempt to be blocked if it collides with a similar object.

All my attempts at using collisions (script attached to the prefab of the object, using OnCollisionEnter or OnTriggerEnter) failed.

Decided to try an other route, which would be to use a grid of this "game area" and store in an array the state of every cell of the grid, so haveing the mouse snap to the grid and then check if the cells are already in use by an object or not (not sure exactly how to create that grid though).

Any way, does anyone have suggestions regarding which method would be best, and a bit of code to get me started please?

Thanks in advance!

No code (you'll have to do that yourself) but your approach is not bad. If you can separate your terrain layout in discrete segments - and that's more of a design decision than a technical one - that would be a way to do it. You may want to consider sparse arrays, as I imagine the vast majority of spots will be "empty".

If you don't wish to separate it in discrete segments, you can:

  1. Make sure your raycast is hitting the terrain, and not another tower's collider.
  2. Keep a list of tower positions. Before placing a tower where the user clicked, ensure that the position is at least X units from other towers placed (where X is the tower radius).

Which would stop your towers from overlapping.