- Home /
How to make objects snap on a grid with a raycast?
I'm making a first person farming game, and I'm using a raycast to do actions like grabbing objects and planting vegetables. At the moment I'm able to plant vegetables on the position of the raycast hit. I need to plant the vegetables on a field, so I'd like to instantiate them on a grid. I found very few tutorials to do so, and no one explained how to instantiate only one object on one point of the grid. Any help would be appreciated.
Answer by Captain_Pineapple · Jul 18, 2021 at 05:23 PM
hey there,
given info you provided and since you are already able to place objects you basically just have to round the positions to your grid.
you can use this following function to convert a random position to a snapped grid position:
public Vector3 getPositionOnGrid(Vector3 pos)
{
float gridsize = 5f;
var tmpY = pos.y;
pos = pos / gridsize;
return new Vector3(Mathf.Floor(pos.x) + 0.5f , tmpY, Mathf.Floor(pos.z)+ 0.5f)* gridsize;
}
This should give you the center of the grid tile of this tho given Vector in the x-z axis keeping its original y coordinate.
Note that this is not tested.
cool, thx for letting us know. Can you mark this as the accepted answer so that other can see that this was correct? Cheers
Your answer
Follow this Question
Related Questions
Is RaycastHit an expensive operation vs something via JS? 1 Answer
How do you save a seed? 1 Answer
Sorting the children of a Grid Layout in 4.6 UI 3 Answers
Manual Collision Detection through triggers... 0 Answers
fixed angle grid movement issue 1 Answer