Skip to content

Instantly share code, notes, and snippets.

@TheFizz
Created June 4, 2020 02:57
Show Gist options
  • Save TheFizz/2a5eb9f2109523132c7ff00e25966b6d to your computer and use it in GitHub Desktop.
Save TheFizz/2a5eb9f2109523132c7ff00e25966b6d to your computer and use it in GitHub Desktop.
This script will "voxelize" the existing MagicaVoxel model in Unity3D so you can "shatter" it in voxel cubes.
using System;
using System.Collections.Generic;
using UnityEngine;
public class Voxelizer : MonoBehaviour
{
public GameObject parent;
public GameObject voxel;
private float height, width;
Collider meshCollider;
void Start()
{
Voxelize();
}
public void Voxelize()
{
float voxelSize = 0.1f;
meshCollider = gameObject.GetComponent<MeshCollider>();
height = (float)Math.Round(meshCollider.bounds.size.y, 2);
width = (float)Math.Round(meshCollider.bounds.size.x, 2);
var startPoint = meshCollider.bounds.min + new Vector3(voxelSize / 2, voxelSize / 2, voxelSize / 2);
var direction = Vector3.forward;
for (float z = 0; z < width; z += voxelSize)
{
for (float x = 0; x < width; x += voxelSize)
{
for (float y = 0; y < height; y += voxelSize)
{
var testPoint = startPoint + new Vector3(x, y, z);
if (CheckInside(testPoint, meshCollider.bounds.min))
{
var tmp = Instantiate(voxel, testPoint, Quaternion.identity, parent.transform);
}
}
}
}
}
public bool CheckInside(Vector3 point, Vector3 startPoint)
{
Physics.queriesHitBackfaces = true;
float rayThreshold = 0.01f;
float deltaX, deltaY, deltaZ;
deltaX = (float)Math.Round(point.x - startPoint.x, 2);
deltaY = (float)Math.Round(point.y - startPoint.y, 2);
deltaZ = (float)Math.Round(point.z - startPoint.z, 2);
var ups = Physics.RaycastAll(point, Vector3.up, height - deltaY + rayThreshold);
var fronts = Physics.RaycastAll(point, Vector3.forward, width - deltaZ + rayThreshold);
var rights = Physics.RaycastAll(point, Vector3.right, width - deltaX + rayThreshold);
var downs = Physics.RaycastAll(point, Vector3.down, height - (height - deltaY) + rayThreshold);
var backs = Physics.RaycastAll(point, Vector3.back, width - (width - deltaZ) + rayThreshold);
var lefts = Physics.RaycastAll(point, Vector3.left, width - (width - deltaX) + rayThreshold);
Physics.queriesHitBackfaces = false;
if (ups.Length > 0 && fronts.Length > 0 && rights.Length > 0 && downs.Length > 0 && backs.Length > 0 && lefts.Length > 0)
return true;
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment