I am trying to make a game where you have a flat world and you use a,w,s,d and up and down arrow to rotate the camera round and zoom in and out and i have all that done and what i am trying to do is get it so the person playing the game can place and destroy blocks on the terrai nwith in the grid. but all i can get it to do is place them at the centre of the screen could some one please give me some help? as i am not very good at coding.
1 Answer
1like this:
var prefab : Transform;
function Update(){
if(Input.GetMouseButtonUp(0)){
var ray : Ray = camera.ScreenPointToRay (Input.mousePosition);
var hit : RaycastHit;
if (Physics.Raycast(ray, hit,Mathf.Infinity)){
if(hit.collider.tag == "Terrain"){
var placePos : Vector3 = hit.point;
placePos.y += .5;
placePos.x = Mathf.Round(placePos.x);
placePos.z = Mathf.Round(placePos.z);
Instantiate (prefab, placePos, Quaternion.identity);
}
}
}
}
you will need to set up the tag on your terrain for this to work, or get rid of that line…
EDIT: updated the code to attempt to achieve the desired grid behavior… I think this should pretty much work…
ok thank you for that dose that do anything or is just to show me how to use the mouse position? just so then i know what i need to do.
– ApplezGamingthis should work, as long as you: 1- set the var "prefab" to the object you want to set 2- create a new tag called "Terrain", and give your terrain that tag the terrain also needs a mesh collider
– Seth-Bergmanok thank you it dose work but the block is place half in the ground and isnt placed in the grid could you help with that maybe please?
– ApplezGamingThis is because the position of the block is in the middle of it. So you need to lift it up half of its height on the y-position for it to rest properly on the ground.
– fafaseoh ok thanks you i will try that but what about x and z axes?
– ApplezGaming