Unique placement in a cell on the terrain


I’m trying to make a Tower Defense game and after some trys to implement a placement system I considered to ask you.

My goal: I need a placement grid in which every cell can only be used once (or restored to empty when the tower is destroyed/reassigned to another cell).

I tried to make a “virtual” grid and place buildings. Everything works, the towers spawn at the surface, just the cells can hold more than 1 building.

My used code until now:

var gridX : float= 5;
var gridY : float= 5;
var placementLayerMask : LayerMask;
var cannon1 : GameObject;

function Update(){

function Build()
	var ray = Camera.main.ScreenPointToRay (Input.mousePosition);
	var hit : RaycastHit;
	var P : Vector3= hit.point;        
	if (Physics.Raycast (ray, hit, 100, placementLayerMask))
		P = hit.point;
		P.x = Mathf.Floor(P.x/gridX) * gridX + gridX/2;
		P.y = P.y;
		P.z = Mathf.Floor(P.z/gridY) * gridY + gridY/2;
		Instantiate(cannon1, P+ Vector3(0,cannon1.transform.position.y,0),Quaternion.identity);

My first idea was to store the cellId (P.x,P.z) in an array and search it everytime the mouse is clicked. But somehow I failed and have no clue what to do.

Thanks in advance for a hint/answer.

Since you’re doing a raycast anyway, you could just chuck a collider on your towers and check if you hit one when trying to place.

You might end up with edge cases at the borders though, so I think I’d go with an array of bools or something.

Looks like you already sorted you logic for getting coordinantes, so something like

bool[] occupied = new bool[gridX, gridY];

if(!occupied[P.x,P.z]) {
    occupied[P.x,P.z] = true;

should get you going. Then set to false when you remove a tower.