- Home /
2D grid for building
Hello,
I try to make a 2D building game. The part of the code is supposed to Instantiate a cube wherever the player clicks. But it must be aligned as a grid (2D minecraft).
The problem is that the "Mathf.FloorToInt" I use converts for example the float "0,2" -> "0", so the Cube is instantiated one unit to the left, not on the part of the grid the user clicks.
Any help?
#pragma strict
var block : GameObject;
function Update () {
var pos : Vector3 = Camera.main.ScreenToWorldPoint(Input.mousePosition);
var posIntX : int = Mathf.FloorToInt(pos.x);
var posIntY : int = Mathf.FloorToInt(pos.y);
if(Input.GetMouseButtonDown(0))
{
Instantiate(block,Vector3(posIntX,posIntY,0),transform.rotation);
}
}
If the X axis is the problem then:
you can use ceiling ins$$anonymous$$d of flooring (not sure that such function exists)
or the easy one:
var posIntX : int = $$anonymous$$athf.FloorToInt(pos.x) + 1;
The problem is on both axis, if I click < .5 it rounds it to 0. if I click > .5 it rounds it to 1
this depends on the pivot point of your block. I assume you are using a standard cube which has its pivot in the center. If you made the cube a child of an empty gameObject, and position it locally to (0.5,0.5,0.5) then the cube would sit where you want it.
alternatively, you could modify your equation to account for the pivot of the cube :
var posIntX : int = $$anonymous$$athf.FloorToInt(pos.x+0.5);
var posIntY : int = $$anonymous$$athf.FloorToInt(pos+0.5);
//
Instantiate(block,Vector3(posIntX,posIntY,0.5),transform.rotation);
Thanks every one, I found a solution. Posted as an answer!
Answer by smirlianos · Apr 14, 2014 at 11:41 AM
var Block:GameObject;
var squareSize : float = 1.0f;
function Update () {
if (Input.GetMouseButtonDown(0))
{
var mousePos : Vector3 = Input.mousePosition;
mousePos.z = 10;
var objectPos : Vector3 = Camera.main.ScreenToWorldPoint(mousePos);
objectPos.x = Mathf.Round(objectPos.x/squareSize) * squareSize;
objectPos.y = Mathf.Round(objectPos.y/squareSize) * squareSize;
objectPos.z = Mathf.Round(objectPos.z/squareSize) * squareSize;
Instantiate(Block, objectPos, Quaternion.identity);
}
}