Skip to content

Instantly share code, notes, and snippets.

@imerr

imerr/tree.cs Secret

Created January 27, 2020 17:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save imerr/e95bedb0bed8c3b4e41f311b9f3d6eb1 to your computer and use it in GitHub Desktop.
Save imerr/e95bedb0bed8c3b4e41f311b9f3d6eb1 to your computer and use it in GitHub Desktop.
void CollectTreeMeshes (Terrain terrain, List<RasterizationMesh> result) {
TerrainData data = terrain.terrainData;
for (int i = 0; i < data.treeInstances.Length; i++) {
TreeInstance instance = data.treeInstances[i];
TreePrototype prot = data.treePrototypes[instance.prototypeIndex];
// Make sure that the tree prefab exists
if (prot.prefab == null) {
continue;
}
var treePosition = terrain.transform.position + Vector3.Scale(instance.position, data.size);
var scale = new Vector3(instance.widthScale, instance.heightScale, instance.widthScale);
scale = Vector3.Scale(scale, prot.prefab.transform.localScale);
bool colliderFound = false;
void TreeCollider(Collider collider) {
colliderFound = true;
// The prefab has a collider, use that instead
// Generate a mesh from the collider
RasterizationMesh mesh = RasterizeCollider(collider, Matrix4x4.TRS(treePosition, Quaternion.identity, scale));
// Make sure a valid mesh was generated
if (mesh != null) {
// The bounds are incorrectly based on collider.bounds.
// It is incorrect because the collider is on the prefab, not on the tree instance
// so we need to recalculate the bounds based on the actual vertex positions
mesh.RecalculateBounds();
result.Add(mesh);
}
}
foreach (var collider in prot.prefab.GetComponents<Collider>()) {
TreeCollider(collider);
}
foreach (var collider in prot.prefab.GetComponentsInChildren<Collider>()) {
TreeCollider(collider);
}
if (colliderFound) {
var instanceBounds = new Bounds(terrain.transform.position + Vector3.Scale(instance.position, data.size), new Vector3(instance.widthScale, instance.heightScale, instance.widthScale));
Matrix4x4 matrix = Matrix4x4.TRS(treePosition, Quaternion.identity, scale*0.5f);
var mesh = new RasterizationMesh(BoxColliderVerts, BoxColliderTris, instanceBounds, matrix);
result.Add(mesh);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment