Placing a 2x2 tower around node nearest mouse click

Hi,

I just started using this project yesterday and am fairly new to Unity as a whole. I am creating a TD with mazing.

Some info: Using a grid graph with node size set to 0.5. The graph is over a terrain object.

Say the player clicks where the red dot is. I then want a 2 node by 2 node tower to be placed where the blue box in. . Here’s the current code for this, that just places a tower on the nearest node to click:

void OnMouseUpAsButton() {
	RaycastHit hitInfo;
	Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
	Physics.Raycast(ray, out hitInfo, Mathf.Infinity, LayerMask.GetMask("Ground"));
	Vector3 clickposition = hitInfo.point;

	GraphNode node = AstarPath.active.GetNearest (clickposition).node;
		
	GameObject g = (GameObject)Instantiate(towerPrefab);
	g.transform.position = (Vector3)node.position + Vector3.up;
	var guo = new GraphUpdateObject (GetComponent<Collider> ().bounds);
	guo.updatePhysics = true;
	AstarPath.active.UpdateGraphs (guo);
}

I have the A* object as well as the terrain layer set to “Ground”.

Hi

Are you sure the tower is being detected as an obstacle?
Try to place a tower and then scan the graph from the inspector. If it does not make some nodes unwalkable, make sure that the tower’s layer is included in the Grid Graph -> Collision Testing -> mask field.

Hi, tried to ninja edit my post but you’re fast! I actually had the script attached to the wrong object so that’s why nothing was placed (oops). Now it is placing towers and making the areas around them unwalkable. My follow up question is this, suppose I have my towers like in the picture. I want the area between them to be walkable. I have the collision testing to be 0.49 diameter and my tower’s box collider is 1x1x1. I want that half block area in between to be a possible path.

Hi

Since you are placing a 2x2 tower, I suggest that you offset your towers’ positions by (0.5,0.5) node sizes because right now it is covering 3x3 nodes. If you want it to cover 2x2 nodes then the center of the tower cannot be the center of a node.

var graph = AstarPath.active.astarData.gridGraph;
g.transform.position = (Vector3)node.position + Vector3.up + new Vector3(0.5f*graph.nodeSize, 0, 0.5f*graph.nodeSize);

The above code might cause the mouse snapping to be a bit biased, but I think it should place the towers on the correct positions at least.

Ah there has been the big problem I think. I didn’t realize I was covering too many nodes like that. The only issue is now the node.walkable check I had before instantiating isn’t working anymore, I think because the tower is moving slightly after the check.