- Home /
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.
Picture related - I'd like to know over which hexes the white box is.
Answer by robertbu · Jun 09, 2013 at 09:44 PM
This is a harder problem, and I cannot think of a perfect solution. What you could do is:
Do a raycast or just a calculation to find the hex that contains the center of the overlaying game object.
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.
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.
I only need this as a dev tool, so that after creating/updating the scene I will be able to one-time run this method and it will save the results to a text file or something, so performance is not an issue for me.
I also thought about making an empty object with a sphere collider and jumping with it through all the hexes on the map. Sadly I don't know how to 'manually' check the collisions and the for loop is too fast for OnTriggerEnter/OnTriggerStay to catch any collisions.
You can use Physics.SphereCast() to cast your sphere. No need to use a real sphere collider. Note the SphereCast() will miss the corners. If this is an edit time tool, you could just do a SphereCast() and/or Raycast() for all the hex positions and not worry about flood-fill-like behavior.