5
« on: September 15, 2014, 08:24:16 PM »
The Boolean operations were written to be performed while in editor mode but the classes are public so you can adapt the following script to perform the operations during runtime:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using CSG;
public class Test : MonoBehaviour
{
public enum Operation { Subtract, Union, Intersection };
List<Polygon> origPolygons;
GameObject gameObjectA;
GameObject gameObjectB;
Transform[] childs = new Transform[2];
public Operation operation = Operation.Subtract;
// Use this for initialization
void Start ()
{
gameObjectA = GameObject.Find("Target");
gameObjectB = GameObject.Find("Brush");
childs[0] = gameObjectA.transform;
childs[1] = gameObjectB.transform;
origPolygons = new List<Polygon>();
CSG.CSG.triIndex = 0; // always set this to zero before all operations
CSG.CSG.transform = gameObjectA.transform;
CSG.CSG A = CSG.CSG.fromMesh(childs[0].GetComponent<MeshFilter>().sharedMesh, childs[0], true);
CSG.CSG B = CSG.CSG.fromMesh(childs[1].GetComponent<MeshFilter>().sharedMesh, childs[1], false);
origPolygons.AddRange(A.polygons);
origPolygons.AddRange(B.polygons);
CSG.CSG result = null;
if (operation == Operation.Subtract)
{
result = A.subtract(B);
}
if (operation == Operation.Union)
{
result = A.union(B);
}
if (operation == Operation.Intersection)
{
result = A.intersect(B);
}
if (result != null)
{
result.toMesh(gameObjectA, gameObjectB);
}
}
// Update is called once per frame
void Update ()
{
}
}
To use the code start by copying the following three DLLs to your project folder:
MeshMaker.dll
ComputationalGeometry.dll
VectorGeometry.dll
(or just the BooleanOps.dll if you don't have MeshMaker)
Then attach the script above to a new empty game object.
Create two new cubes and rename them to "Target" and "Brush".
Position the cubes so that they are intersecting and click the play button.