- Home /
Building using raycasts similar to Minecraft
I'm trying to create a game, where you can build around the world using raycasts, this game should look similar to minecraft (in the building aspect)
Here is my code:
{
public Transform blocktrans;
public GameObject block;
public Vector3 offset;
public float x;
public float y;
public float z;
public Vector3 pos;
public Renderer blockrend;
// Start is called before the first frame update
void Start()
{
transform.position = new Vector3(Mathf.Round(transform.position.x), Mathf.Round(transform.position.y), Mathf.Round(transform.position.z));
}
// Update is called once per frame
void Update()
{
if (block.name != "BuildingBlock")
{
blockrend.enabled = true;
}
else
{
blockrend.enabled = false;
}
var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out RaycastHit hit))
{
x = (hit.point.x);
y = (hit.point.y);
z = (hit.point.z);
pos = new Vector3(x, y, z);
if (Input.GetMouseButtonDown(0))
{
if (block.name == "BuildingBlock")
{
blocktrans.position = pos;
Instantiate(block);
}
}
}
}
}
Comment
Your answer
Follow this Question
Related Questions
MaK like building script help... 0 Answers
Why can't I build Web Player in Unity while I have no problems with building standalone versions? 2 Answers
Trouble with Minecraft like building 0 Answers
Can someone fix this building and breaking code? 0 Answers
Help! Saving blocks in a grid-based building system 0 Answers