- Home /
Help with placing and destroying blocks
I got these scripts here:
var blockLayer : LayerMask = 1; var range : float = Mathf.Infinity; var hit : RaycastHit;
function Update () { if (Input.GetMouseButtonDown(0)) Build(); if (Input.GetMouseButtonDown(1)) Erase(); }
function Build() { if (HitBlock()) { var cube = GameObject.CreatePrimitive(PrimitiveType.Cube); cube.transform.position = hit.transform.position + hit.normal; } }
function Erase() { if (HitBlock()) Destroy(hit.transform.gameObject); }
function HitBlock() : boolean { return Physics.Raycast(transform.position, transform.forward, hit, range, blockLayer); }
and
for (var y = -4; y < 5; ++y) for (var x = -4; x < 5; ++x) { var cube : GameObject = GameObject.CreatePrimitive(PrimitiveType.Cube); cube.transform.position = transform.position + Vector3(x, 0, y); }
I want the player to not be able to destroy the terran such as a plane, right now it just destroys the game object. If you don't know how to do that if I could just color the cube floor or add a picture to it as if it was a plane then that would be great too.
Sorry I am new to unity and not the best with javascript.
Answer by robertbu · Feb 05, 2013 at 06:05 AM
In the future you need to format your code using the "101/010" labeled button. If the code is not easily readable, then your are far less likely to get any help.
I have difficulty understanding your question. What I think you want is that destroying should be limited to blocks, so other elements like the plane are not destroyed when clicked on. One way would to create a tag in the tag manager...something like "Block". Then right after you create the block you would code:
cube.tag = "Block";
And then when you check for a hit you could do something like:
function HitBlock() : boolean {
if (Physics.Raycast(transform.position, transform.forward, hit, range, blockLayer)) {
if (hit.collider.gameObject.tag == "Block")
return true;
}
return false;
}
That way, only game objects with the "Block" tag would be destroyed.