Make array of object based on position

Hey guys, I’m attempting to make a simple array of objects based on their x and y position. Been having some brain farts back and forth so figured I’d take a stab on here.

Their positions are not snapped to a grid, so I’m unable to use their transform position values. What’s the best way to fill the array based on position relative to one another?

Thanks!

Unless the positions don’t have an one to one relation with int pairs you can’t. At least I can’t think of a viable way to do this.
Question is why, given the lack of absolute positions?

Well they have a relation, as it will be a grid of objects, just their positions are dynamic and wont be round or reliable.

Their relationship to eachother would, though.

Well as mentioned you need an one to one relationship between indexes and positions.

Something like this for example.

Vector2Int GetObjectsTileCoords(Vector3 objPos, float tileSize)
{
var xIndex = Mathf.FloorToInt(objPos.x/ tileSize);
var yIndex = Mathf.FloorToInt(objPos.y/ tileSize);
return new Vectror2Int(xIndex, yIndex);
}

This is what I was initially thinking, but my grid objects can be less than a unit in size: IE I could have one at (1x,1y) another at (1.2,1.2) then (1.4,1.4). Wanting to sort that to [1,1][1,2][1,3]

With dynamic starting sizes, though. So that same grid could be (1x,1y) (1.4,1.4) (1.8,1.8)

I dunno I’m all over the place I may need to rethink things :slight_smile:

Just did this last weekend, made a grid of enemies in the X/Z plane. Here’s the grid maker:

    void CreateEnemyGrid( Transform grid, int across, int down)
    {
        var xSpacing = grid.localScale.x;
        var zSpacing = grid.localScale.z;

        for (int j = 0; j < down; j++)
        {
            for (int i = 0; i < across; i++)
            {
                Vector3 pos = grid.position + grid.right * i * xSpacing + grid.forward * j * zSpacing;

                MakeFreshDudeAt(pos);  // you supply
            }
        }
    }

Pass in the Transform of where you want the (0,0) guy to be.

Set the scale of that Transform to X and Z being the spacing in X and Z

Set the rotation of the Transform to how you want to align it.

Call the method like so:

        CreateEnemyGrid(
            rootOfFormation,
            8,
            3);

Could be trivially extended:

  • make 3 nested loops to have a 3D formation
  • change any of the axes to be something else (like X/Y)
  • pass the rotation into the MakeDude method so he knows which way to face.
  • etc.
1 Like