- Home /
Problem at Minecraft like game
Hello I am programming a game like Minecraft. My problem is that I cant place blocks how i want it.
Here you can see that I am ponting on a block and want to place another block infront of it. The red line in the Scene view is the line were I am pointing at and the blue line is the line were the game wants to place the block.
My script for this is:
using UnityEngine;
using System.Collections;
public class PlaceBlock2 : MonoBehaviour {
public float range = 5;
public Transform prefab;
RaycastHit hit;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
Ray ray = Camera.main.ScreenPointToRay (new Vector3(Screen.width*0.5f, Screen.height*0.5f, 0f));
if (Physics.Raycast(ray, out hit,range)){
// Pointing Ray
Debug.DrawLine(transform.position,hit.point,Color.red);
// Point to place
Vector3 V = new Vector3(Mathf.Round(hit.point.x), Mathf.Round(hit.point.y+0.5f), Mathf.Round(hit.point.z));
// Place Ray
Debug.DrawLine(transform.position,V,Color.blue);
// Place Block
if(Input.GetMouseButtonDown(0)){
Instantiate(prefab,V, Quaternion.identity);
}
}
}
}
Is my point to place wrong or were is my error.
Answer by Cherno · Jan 07, 2015 at 09:46 PM
You could try using Mathf.Floor, or determine a point that is slightly inside the cube you are hitting by taking the hit.point and adding the camera's transform.forward * 0.01f to it, and then rounding this point instead. Besides that, take a look at the After playing Minecraft... thread, there are more sultions to your problem included.
adding the camera's transform.forward * 0.01f to it
I dont understand were I have to add it
You have the hit.point. Now, you declare a new Vector3 and assign it the hit.point value plus the camera's transform.forward * 0.01f:
Vector3 blockPos = hit.point + cameraObject.transform.forward * 0.01f;
blockPos = new Vector3($$anonymous$$athf.FloorToInt(blockPos.x),$$anonymous$$athf.FloorToInt(blockPos.y),$$anonymous$$athf.FloorToInt(blockPos.z));
Again the same problem -.- I need something that round to x.5( if 1.3 than 1.5 and when 1.9 than 1.5 too)
Answer by jpthek9 · Jan 07, 2015 at 09:50 PM
You need 2 booleans to see which way to round to for the mine craft placement system.
bool XPositive = hit.point.y > hit.transform.position.y ? true : false;
bool XNegative = hit.point.x > hit.transform.position.x ? true : false;
If you need more help, just ask and I'll explain further.
Answer by gamer_bros_64 · Sep 11, 2020 at 10:20 AM
that kinda worked , but the blocks still place inside each other. plus they dont always work still. maybe try adding a line that says if a block in a piece of the grid is 1 then dont place there.
Your answer
Follow this Question
Related Questions
Most efficient method to create mesh from array 1 Answer
UV mapping 5 Answers
Using Meshes To Generate Cube Word? 2 Answers
Minecraft style pixels 1 Answer