Game Object - world space to grid coordinates

I’ve asked this question once but made it unclear so I want to rephrase it.

I have a way of converting world position to hex coordinates. Hex map is stored as a 2D array and it’s represented on the scene via a projected green hex grid. I want to know what hex fields are ‘occupied’ by game objects on the scene.

alt text

Picture related - I’d like to know over which hexes the white box is.

This is a harder problem, and I cannot think of a perfect solution. What you could do is:

  1. Do a raycast or just a calculation to find the hex that contains the center of the overlaying game object.
  2. Recursively walk outward from the found hex and raycast upward from the center of the each adjacent hex. Note since you are checking a specific object at this point, you can do a a cheaper Collider.Raycast(), rather than a Physics.Raycast(). The walk outward is similar to a flood fill algorithm.
  3. If the Raycast() fails, you will need to do a check for partial coverage. Doing a Collider.Raycast() from the six corners of the hex will get most objects. Doubling it to 12 raycasts should get almost all objects. You could use a Physics.SphereCast() if you wanted extra insurance against very narrow objects, but no combination will be 100 percent sure, and performance may be an issue.