Return grid points within a cube selection

I’m working on a voxel based level editor for Unity and have run into a problem with building.

I need to define a cuboid selection with two Marker voxels and return the valid grid points within said cube.

Here’s an example:
Green is Marker 1, Red is Marker 2, I need to return the grid points that the black blocks are occupying.
alt text

While my example is a 2D rectangle, this should also work for cuboid selections.

For reference my grid spacing is 0.5. So the possible points would look something like (0,0,0), (0,0.5,0), (0,1,0) and so on…

Any help is greatly appreciated!

Ok, this one is reasonably tough.
If I understand correctly, you’re trying to get the “GridPositions” of each block between Green Marker 1 and Red Marker 2.

So, for example, if you have:

  • Green Marker (0,0,0)
  • Red Marker (1,1,0)

That would lead to the Grid points:

  • (0,0,0)
  • (0,0.5f, 0)
  • (0, 1, 0)
  • (0.5f, 0, 0)
  • (1, 0, 0)
  • (0.5f, 0.5f, 0)
  • (0.5f, 1, 0)
  • (1, 0.5f, 0)
  • (1, 1, 0)

Also, I take it you’re ignoring the Z axis for now.

So, we’ll need a method that does this for us.
Let’s say it returns a list of Vector3, representing the GridPositions.
And we’ll define the GridSeperation as a public float, here you go:

public float gridSeperation = 0.5f;

public List<Vector3> GetOccupiedGridPoints(Vector3 greenMarkerPos, Vector3 redMarkerPos)
    // Make a holder
    List<Vector3> temp = new List<Vector3>();

    // Get the difference Vector betwen the two markers
    Vector3 deltaPos = (redMarkerPos - greenMarkerPos);

    // Calculate how many blocks in Width and Height there are between the markers
    int blocksInWidth = Mathf.RoundToInt(deltaPos.x / gridSeperation);
    int blocksInHeight = Mathf.RoundToInt(deltaPos.y / gridSeperation);

    // Use a double for loop to run through each block and add it's position
    for (int x = 0; x < blocksInWidth; x++)
        for (int y = 0; y < blocksInHeight; y++)
            // Add the position to the list
            temp.Add(new Vector3(greenMarkerPos.x + x * gridSeperation, greenMarkerPos.y + y * gridSeperation, greenMarkerPos.z));

    // Return the list
    return temp;

This was only a quick guess, but it could be right on the money.
I hope it helps out, give it a shot! :wink:

Oh and, if you haven’t used Lists before, make sure to add:
“using System.Collections.Generic;” At the top of your script to allow List<> variables :slight_smile: