#Unexpected behavior from GridLayout.WorldToCell()

1 messages · Page 1 of 1 (latest)

unique dove
#

Hello,

I am trying to make a script that calculates the size of a prefab's collider, then converts that size into grid units for a building system. To do this, I am creating an array of Vector3Int[4] using the size of the prefab's colliders. I then use GridLayout.WorldToCell() on each vector to get a grid coordinate value. Finally, I subtract these grid values to get the size of the object in grid units.

Here is the code:

private void GetColliderVertexPositionsLocal() // Returns an array of vectors representing the four corners of the collider.
{
    BoxCollider b = gameObject.GetComponent<BoxCollider>();
    Debug.Log(b.center);
    Vertices = new Vector3[4];   
}

private void CalculateSizeInCells() // Gets the size of the collider measured in cells
{
    Vector3Int[] vertices = new Vector3Int[Vertices.Length];

    for (int i = 0; i< Vertices.Length; i++)
    {
        vertices[i] = BuildingSystem.current.gridLayout.WorldToCell(Vertices[i]);
    }

    int SizeX = Mathf.RoundToInt((vertices[0] - vertices[1]).magnitude);
    int SizeZ = Mathf.RoundToInt((vertices[0] - vertices[3]).magnitude);
    Size = new Vector3Int(SizeX, 1, SizeZ);
}

Here's where I'm encountering issues. The grid is a child of a rocking platform. So the rotation changes. In my tests, I've been setting the X rotation to -30 degrees in the inspector. When I do so, the vertices are converting to grid units with different values than they are when the platform is flat. This confuses me, because the Vertices[] (capital V) array values are exactly the same. So I don't understand why the vertices[] values should calculate any differently.

I have lots of debug.logs that were deleted for space. But here are some of the values from tests.

#

Here is the values when the parent platform and grid are flat (no rotation). These results seem right to I've highlighted the values that change unexpectedly.

#

Here are those same logs when the parent platform is at a x rotation of -30.

#

Notice how the Vertices[3] values (BIG V) is the same, but the vertices[3] (little v) value changes. This is my main issue. This same issue happens to different combinates of vectors if the plane is rotated in a different direction. But I believe this all stems from the same issue. What am I not understanding about WorldToCell() that causes this?

Any help is greatly appreciated.