Voxelizing a mesh in Unity was quite a bit easier than anticipated. After doing a quick search I found this article by David Rosen of Wolfire. He details the method for creating a voxelized grid, checking each part of the grid to see if it intersects part of the mesh, and adding a voxel for each intersection. There was no code accompanying his article, but after reading it I decided it would be fairly straightforward to write my own voxelizer in Unity3d.
I started out by creating a prefab with a cube mesh and box collider attached to it. This is our voxel.
Then I created an object with a sphere mesh and added a mesh collider to it. This is the object we’re going to voxelize
The 3rd element was a separate box collider that is slightly bigger than the sphere. This is used as the bounds of our voxelization grid.
The plan was to spawn a voxel, move it to each point in the grid, and if it was colliding with the mesh a voxel would be spawned. Unfortunately, this didn’t work because the SweepTest method I was using didn’t register collisions with MeshColliders. Fortunately, Raycasts collide with MeshColliders so I set up some loops to Raycast along each edge of a cube in both the positive and negative directions (See pic).
Turns out this works fairly well. Here’s the result of voxelizing a sphere:
After refining a few things like being able to set the voxel size and colors I created this neat little video:
I’m planning to use this tech in my next game, which I’ll be revealing very soon.