Skip to content

Instantly share code, notes, and snippets.

@r8n5n
Created January 22, 2016 16:19
Show Gist options
  • Save r8n5n/d18b8009163577363b45 to your computer and use it in GitHub Desktop.
Save r8n5n/d18b8009163577363b45 to your computer and use it in GitHub Desktop.
Pick a random point within a triangle
/**
* Pick a random point within a triangle
* @param {Object} a Point {x:# , y:#}
* @param {Object} b Point {x:# , y:#}
* @param {Object} c Point {x:# , y:#}
* @returns Object {x:# , y:#}
*
* @see http://parametricplayground.blogspot.co.uk/2011/02/random-points-distributed-inside.html
*/
randomPointInTriangle: function (a, b, c) {
var rc = 0,
px,
py,
ra = Math.random(),
rb = Math.random();
if (ra + rb > 1){
ra = 1 - ra;
rb = 1 - rb;
}
rc = 1 - ra - rb;
px = (ra * a.x) + (rb * b.x) + (rc * c.x);
py = (ra * b.y) + (rb * b.y) + (rc * c.y);
return {x: px, y: py};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment