I want to be able to move objects on a grid always by what the grid cell size is, and objects bigger than the grid size should not overlap.
The cube in this GIF below is snapping how I want (1 x 1).
If I then change the size of the object, it doesn't snap to the grid quite how I would like. It snaps, but overlaps. I don't want an object to overlap the grid cell.
The snapping code is pretty straight forward and has been posted quite a lot and seems to work fine.
pos.x = Mathf.Round(hit.point.x + (hitNormal.x * objScale.x)) * gridSize; pos.y = Mathf.Round(hit.point.y + (hitNormal.y * objScale.y)) * gridSize; pos.z = Mathf.Round(hit.point.z + (hitNormal.z * objScale.z)) * gridSize;
I was thinking that I need to somehow set a pivot / anchor point, but I wouldn't want that to be one corner of the object, I was thinking somehow I could find the center of the object and work from there so it can snap correctly. Not sure if this is correct, or how to work that out.
Edit: More code added to show how I am moving objects around currently.
Objects are placed in the world by ray casting. I don't use any grid array to know the location of objects on the grid.
For placement testing (i.e object inside another) this is handled already but removed that part of the code. For that I am doing a simple box overlap test which works nicely.
float gridSize = 1f; Vector3 hitNormal = hit.normal.normalized; Vector3 localObjScale = transform.localScale; // - "Determine the minimum grid space this shape will use up" // Objects will always be whole numbers. i.e 2w x 1h x 1l (like second GIF) int cellWidth = Mathf.RoundToInt(localObjScale.x); int cellsHeight = Mathf.RoundToInt(localObjScale.y); int cellsLength = Mathf.RoundToInt(localObjScale.z); Vector3 objScale = localObjScale / 2f; // This sets the pivot to the center Vector3 pos = Vector3.zero; // Snap pos.x = Mathf.Round(hit.point.x + (hitNormal.x * objScale.x)) * gridSize; pos.y = Mathf.Round(hit.point.y + (hitNormal.y * objScale.y)) * gridSize; pos.z = Mathf.Round(hit.point.z + (hitNormal.z * objScale.z)) * gridSize; transform.position = pos;