Skip to content

Instantly share code, notes, and snippets.

@hclarke
Created October 28, 2015 15:49
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 hclarke/3614ccd0ce490dfc77ca to your computer and use it in GitHub Desktop.
Save hclarke/3614ccd0ce490dfc77ca to your computer and use it in GitHub Desktop.
random points on meshes
public class RandomThings {
public void CalculateRandomPointsOnMeshes(MeshFilter[] meshFilters, Vector3[] dst, Vector3? direction) {
//find all the meshes
float weight = 0;
foreach (var filter in meshFilters) {
var mesh = filter.sharedMesh;
var vs = mesh.vertices;
for(int i = 0; i < vs.Length; ++i) {
vs[i] = filter.transform.TransformPoint(vs[i]);
}
var tris = mesh.triangles;
for(int i = 0; i < tris.Length/3; ++i) {
var a = vs[tris[i * 3 + 0]];
var b = vs[tris[i * 3 + 1]];
var c = vs[tris[i * 3 + 2]];
Vector3 cross = Vector3.Cross(b - a, c - a);
var dir = direction ?? cross.normalized;
float area = Vector3.Dot(dir, cross); //area of triangle projected onto xz plane. negative if it's facing away from dir
if (area < 0) continue; //skip backward triangles
weight += area;
for(int j = 0; j < dst.Length; ++j) {
var r = Random.Range(0, weight);
if(r< area) {
dst[j] = RandomPointInTriangle(a, b, c);
}
}
}
}
this.area = weight;
}
public Vector3 RandomPointInTriangle(Vector3 a, Vector3 b, Vector3 c) {
float br = Random.value;
float cr = Random.value;
//if outside triangle, map it back in
if(br+cr > 1) {
br = 1 - br;
cr = 1 - cr;
}
float ar = 1 - br - cr;
return a * ar + b * br + c * cr;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment