- Home /
Trouble with Minecraft like building
How would I go about creating a way to build things in a game in a way that is similar to Minecraft but allows for non-cube block dimensions.
I currently have a partially working method but in some instances the object will be not align to an already existing object.
Here is an example.
Here is my current code.
Vector3 TempInstScale = TempInst.transform.localScale;
if(Input.GetKeyDown(KeyCode.Keypad8)) {
TempInstScale.x += 0.2f;
}
if(Input.GetKeyDown(KeyCode.Keypad2) && TempInstScale.x > 0.2f) {
TempInstScale.x -= 0.2f;
}
if(Input.GetKeyDown(KeyCode.Keypad9)) {
TempInstScale.y += 0.2f;
}
if(Input.GetKeyDown(KeyCode.Keypad3) && TempInstScale.y > 0.2f) {
TempInstScale.y -= 0.2f;
}
if(Input.GetKeyDown(KeyCode.Keypad7)) {
TempInstScale.z += 0.2f;
}
if(Input.GetKeyDown(KeyCode.Keypad1) && TempInstScale.z > 0.2f) {
TempInstScale.z -= 0.2f;
}
if(Input.GetKeyDown(KeyCode.Keypad5)) {
TempInstScale = new Vector3(1, 1, 1);
}
TempInst.transform.localScale = TempInstScale;
TempPlaceObj.transform.localScale = TempInstScale;
float GridSize = 0.2f;
if(HotBar[HotBarSlot].Item_Type == Items.ItemType.Block) {
Ray rayplc = cam.ScreenPointToRay(Input.mousePosition);
RaycastHit hitplc;
if(Physics.Raycast(rayplc, out hitplc, 50 + GameObject.Find("PlayerCam").GetComponent<CameraControl>().DistanceToTarget)) {
TempPlaceObj.SetActive(true);
Vector3 pivotpoint = (hitplc.point + hitplc.normal / 2) - hitplc.transform.position;
if(hitplc.collider.tag == "Ground") {
if(TempInstScale.y == 1) {
pivotpoint.y = 0.5f;
}
else
{
pivotpoint.y = TempInstScale.y / 2;
}
}
float tileX = pivotpoint.x / GridSize;
tileX = Mathf.Round(tileX);
float tileY = pivotpoint.y / GridSize;
if(hitplc.collider.tag != "Ground") {
tileY = Mathf.Round(tileY);
}
float tileZ = pivotpoint.z / GridSize;
tileZ = Mathf.Round(tileZ);
float WorldX = hitplc.transform.position.x + tileX * GridSize;
float WorldY = hitplc.transform.position.y + tileY * GridSize;
float WorldZ = hitplc.transform.position.z + tileZ * GridSize;
Vector3 WorldPos = new Vector3(WorldX, WorldY, WorldZ);
TempPlaceObj.transform.position = WorldPos;
if(Input.GetMouseButtonDown(0)) {
Instantiate(TempInst, TempPlaceObj.transform.position, new Quaternion(0, 0, 0, 0));
}
if(Input.GetMouseButtonDown(1) && hitplc.collider.tag == "Block") {
GameObject.Destroy(hitplc.collider.gameObject);
}
}
else
{
TempPlaceObj.SetActive(false);
}
}
else
{
TempPlaceObj.SetActive(false);
}
screenshot 0 .png
(410.2 kB)
Comment
There are probably multiple approaches, but it seems like you could enforce that all objects created in the world are in multiples of your grid size, and then snap those objects to the grid. In other words, if the grid is to allow snapping every 5 world units, then objects need to have a width/height that is always a multiple of 5.