# Increment grid by rotation

I'm currently working on a grid for snapping objects side by side. My current script is working fine, but only for game objects which haven't been rotated.

Here is an example video of the problem:

https://vid.me/jN6D

The cube at the right has a rotation of Vector3.zero, the left one has been rotated on the Y axis.

As you can see snapping works perfectly for the right one, but at 0:15 you can see that the snapping doesn't work well for the rotated cube, that's because I've currently no idea how I can add the rotation in my current script.

Here is a snippet of the most important part of code I'm currently using to calculate the grid:

Vector3 pivotToPoint = hit.point - nearestGameObject.transform.position;

float positionX = nearestGameObject.transform.position.x +
Mathf.Round(pivotToPoint.x / nearestGameObject.transform.renderer.bounds.size.x) *
nearestGameObject.transform.renderer.bounds.size.x;

float positionZ = nearestGameObject.transform.position.z +
Mathf.Round(pivotToPoint.z / nearestGameObject.transform.renderer.bounds.size.z) *
nearestGameObject.transform.renderer.bounds.size.z;

Vector3 origin = new Vector3(positionX, 0, positionZ) + Vector3.up * 100;

if (Physics.Raycast(origin, Vector3.down, out hit, Mathf.Infinity, layerMask)) {
previewGameObject.transform.position = new Vector3(positionX, hit.point.y, positionZ);

previewGameObject.transform.rotation = nearestGameObject.transform.rotation;
}


Maybe some of you guys have an idea how to solve this, it's driving me crazy.

p.s. Here is some guy with a similar problem, but I'm very lost when in comes to adding the solution into my code.