- Home /
grid checking for objects
I have a series of planes set out on my terrain that form a grid on the floor, so far when you click a plane, it spawns a building chosen by the player using building IDs that are selected in the GUI, and all buildings have a box collider of the same size.
What I aim to do is setup some kind of modular building system for the player to mess around with, could anyone tell me how i could check what building is next to it in all 8 adjacent squares around to decide whether a building can be placed on the square thats clicked.
If a different building type is next to it or diagonal to it, it should not be allowed to be placed, otherwise the building will spawn as normal, any help?
Answer by ArkaneX · Aug 20, 2013 at 01:37 PM
I believe you can accomplish it using at least a few approach. Here's my suggestion.
You have to be able to detect the exact location of the plane that user just clicked. To be able to do this, you have to store planes in two-dimensional array:
GameObject[,] planes = new GameObject[gridWidth, gridHeight];
Additionally, you need to add a component to the plane, let's name it PlaneInfo, with three properties: X (int), Z (int), BuildingTypeId (type of your building ID).
When initializing your grid, you have to do something like this:
for(int x = 0; x < gridWidth; x++)
{
for(int z = 0; z < gridHeight; z++)
{
var plane = CreatePlane(); // your code to create plane
var planeInfo = gameObject.GetComponent<PlaneInfo>();
planeInfo.X = x;
planeInfo.Z = z;
planes[x,z] = plane;
}
}
When user clicks on a plane, you have to retrieve its PlaneInfo component, check for its grid coordinates, and check all the planes around it for building IDs:
var planeInfo = clickedPlane.GetComponent<PlaneInfo>();
var x = planeInfo.X;
var z = planeInfo.Z;
bool isBuildingPlaced = false;
// checking planes around
for(int xx = Math.Max(x,0); xx < Math.Min(x,gridWidth-1); xx++)
{
for(int zz = Math.Max(z,0); zz < Math.Min(z,gridHeight-1); zz++)
{
if(xx == x && zz == z)
{
continue; // we don't want to check triggering plane
}
var neighbor = planes[xx,zz];
var neighborInfo = neighbor.GetComponent<PlaneInfo>();
var neighborBuildingTypeId = neighborInfo.BuildingTypeId;
// and now you can check if it is ok to place your building here
// if it is ok, then don't forget to add building id to clicked plane
PlaceBuilding();
planeInfo.BuildingTypeId = buildingTypeIdSelectedInGui;
isBuildingPlaced = true;
break;
}
if(isBuildingPlaced)
{
break;
}
}
Please don't treat above code as a completed one, but rather as a base for your code. I'm not able to test it currently, so it might contains compile errors. But I believe it shows the general concept.