- Home /
I need to Snap a 3d object to a grid when it is placed in game.
Hello Unity answers community. I have looked all over the pages and could not find a script for snapping a 3d object to a grid when placed in the run time. I have a script hat is using a ray-cast to get the position of the courser that is locked at the center of the screen.
var building : GameObject;
var gridX = 5;
var gridY = 5;
var spacing = 2.0;
function Update ()
{
if(Input.GetMouseButtonDown(0))
{
Build();
}
}
function Build()
{
var ray = Camera.main.ScreenPointToRay (Input.mousePosition);
var hit : RaycastHit;
if (Physics.Raycast (ray, hit, 100))
{
Debug.DrawLine (ray.origin, hit.point);
Instantiate(building,hit.point,Quaternion.identity);
}
}
I need the Object (Cube) to be snapped to a grid when the object is spawned in.
Answer by Cherno · May 18, 2015 at 10:47 AM
This is more a basic math question. You need to take the XYZ values of the transform.position and round it to the nearest multiple of you grid size.
There are a lot of examples on the net, here is one that should suit your needs, might need modification due to floating point numbers, but the basic theory is the same:
How to round an integer up or down to the nearest 10 using Javascript
Thanks Cherno But you are right the floating point numbers are my down fall. If there is anyway to not do floating point or geting it appliable for floating point numbers.
Please post comments as comments and answers as answers :) (I converted you answer to a comment).
You can try casting ints as floats with (float)yourInt and use $$anonymous$$ath.RoundtoInt.
Your answer
Follow this Question
Related Questions
Grid snapping 0 Answers
dragging objects horizontally in a grid or in increments 2 Answers
Grids for begginers? 0 Answers
Make grid and snap to it in Unity editor (2D Game) 2 Answers