Hello All,
I am trying to calculate the size of an object in respect to the grid units of a GridLayout. To do this, I am getting a Vector3Int[4] array of all the corners, converting those corners to grid coordinates using WorldToCell, then simply subtracting these cell values to get the length and width of the object in cell units.
However, when I use WorldToCell I am not getting the values I expect.
Here is my code:
private void GetColliderVertexPositionsLocal() // Returns an array of vectors representing the four corners of the collider.
{
BoxCollider b = gameObject.GetComponent<BoxCollider>();
Vertices = new Vector3[4];
//Calculate the coordinates of the object corners using the BoxCollider.Size (in this example, it's 3.9 by 3.9)
Vertices[0] = b.center + new Vector3(-b.size.x, 0, -b.size.z) * .5f;
Vertices[1] = b.center + new Vector3(b.size.x, 0, -b.size.z) * .5f;
Vertices[2] = b.center + new Vector3(b.size.x, 0, b.size.z) * .5f;
Vertices[3] = b.center + new Vector3(-b.size.x, 0, b.size.z) * .5f;
}
private void CalculateSizeInCells() // Converts the size measurement to cell measurement
{
Vector3Int[] vertices = new Vector3Int[Vertices.Length];
for (int i = 0; i< Vertices.Length; i++)
{
vertices[i] = BuildingSystem.current.gridLayout.WorldToCell(Vertices[i]);
}
//Subtract the cell values and store as integers
int SizeX = Mathf.RoundToInt((vertices[0] - vertices[1]).magnitude);
int SizeZ = Mathf.RoundToInt((vertices[0] - vertices[3]).magnitude);
// Store the size as a vector for future use.
Size = new Vector3Int(SizeX, 1, SizeZ);
}
Everything up to the Vertices[] (uppercase V) array seems to be calculating properly. But when I try to calculate the vertices[] (lowercase v) array, I do not get the expected values. I will show an example next.