Random Points In Triangle
/**
* Copyright codeonwort ( http://wonderfl.net/user/codeonwort )
* MIT License ( http://www.opensource.org/licenses/mit-license.php )
* Downloaded from: http://wonderfl.net/c/UESZ
*/
package {
import flash.events.MouseEvent
import flash.display.Graphics
import flash.display.Sprite
import flash.geom.Point
public class FlashTest extends Sprite {
private var a:Point, b:Point, c:Point
public function FlashTest() {
a = new Point(60, 20)
b = new Point(10, 450)
c = new Point(440, 280)
draw(graphics)
stage.addEventListener("mouseDown", redraw)
}
private function redraw(e:MouseEvent):void {
graphics.clear()
draw(graphics)
}
private function draw(g:Graphics):void {
var p:Point
g.lineStyle(1, 0x000000, 1)
g.moveTo(a.x, a.y)
g.lineTo(b.x, b.y)
g.lineTo(c.x, c.y)
g.lineTo(a.x, a.y)
g.lineStyle()
for(var i:int=0 ; i<3000 ; i++){
p = inTriangle(a, b, c)
g.beginFill(0xff0000, 1)
g.drawCircle(p.x, p.y, 1)
g.endFill()
}
}
}
}
import flash.geom.Point
function inTriangle(p0:Point, p1:Point, p2:Point):Point {
var p3:Point = p0.add(p2.subtract(p1))
var v:Point = p0.subtract(p1), w:Point = p2.subtract(p1)
var p:Number = Math.random(), q:Number = Math.random()
var R:Point = new Point
R.x = p1.x + v.x * p + w.x * q
R.y = p1.y + v.y * p + w.y * q
var a:Number = p2.y - p0.y
var b:Number = p0.x - p2.x
var c:Number = -(p0.y * b + p0.x * a)
if(sign(a*p1.x + b*p1.y + c) != sign(a*R.x + b*R.y + c)){
return inTriangle(p0, p1, p2)
}
return R
}
function sign(n:Number):int { return n > 0 ? 1 : n < 0 ? -1 : 0 }