i made a minecraft like game where i need to place block block on a plane i aready figurered out how to place block side to side but now what i whant to do is being able to ceperate a plane in a grid and place my block on the grid insted of in the center of the plane.how can i do this?
here is the block placing part of my script :
var hit : RaycastHit;
var range : float = 15.0f;
var woodBlock:Transform;
function Update () {
if (Input.GetMouseButtonDown(0) && Hit()) {
var cube : Transform = Instantiate(woodBlock);
cube.transform.position = hit.transform.position + hit.normal;
}
if (Input.GetMouseButtonDown(1) && Hit() &&hit.transform.gameObject.tag == "BuildMat"){
Destroy(hit.transform.gameObject);
}
}
function Hit() : boolean {
return Physics.Raycast(transform.position, transform.forward, hit, range);
}
I didn’t understand much your question, but if each cell of your “grid” has the same size (as it definitely should be), then just calculate based on the click position.
Here’s a very small example:
Let’s say cell size is 10 by 10 units
Grid size is 20 cells wide by 20 cells long
Also, let’s say the plane is located to that the (0,0,0) world coordinate is on the lower-left of the plane (just like when you create Terrains). This means the plane itself is not located at (0,0,0), so it’s not “centered”. This is not mandatory but if you change this, you have to add offsets to all calculations.
If the mouse click is at (138, 0, 179) -world position-, then you calculate like so:
cellSize = 10;
mouseX = 138;
mouseZ = 179;
(we ignore mouse Y since we don’t care)
columnClicked = Mathf.Floor(mouseX / cellSize); // in our example, the column clicked is 13
rowClicked = Mathf.Floor(mouseY / cellSize); // in our example, the row clicked is 17
So, at this point, you now the user clicked on the cell located in the coordinate (13, 17). To get the center of it, just add half the cellSize to the position coordinate.
Meaning:
cell 1 starts at X=0 and ends at X=10 horizontally; start at Z=0 and ends at Z=10 vertically
cell 2 starts at X=10 and ends at X=20
and so forth…
so, cell 13 starts at X=130 and ends at X=140
To get the center of the cell add half the size to it. So, the center of cell 13 would be at X=135.
Also, you should use Mathf.Floor or Mathf.Ceil depending if you want the cell coordinate to be zero-based.