Random Points Inside a Triangle

| Comments

just copy and paste the following code:

function getRandomPointInTriangle (A:Point,B:Point,C:Point):Point {

    //P = aA + bB + cC
    //@see http://www.cgafaq.info/wiki/Random_Point_In_Triangle

    var a:Number = Math.random();
    var b:Number = Math.random();

    if (a + b > 1) {
        a = 1-a;
        b = 1-b;
    }

    var c:Number = 1-a-b;

    var rndX:Number = (a*A.x)+(b*B.x)+(c*C.x);
    var rndY:Number = (a*A.y)+(b*B.y)+(c*C.y);

    return new Point(rndX,rndY);
}


var triangleHeight:uint = 150;
var triangleShape:Shape = new Shape();
triangleShape.graphics.lineStyle(1,0xff0000);
triangleShape.graphics.moveTo(triangleHeight/2, 5);
triangleShape.graphics.lineTo(triangleHeight, triangleHeight+5);
triangleShape.graphics.lineTo(0, triangleHeight+5);
triangleShape.graphics.lineTo(triangleHeight/2, 5);
addChild(triangleShape);


var p1:Point = new Point(triangleHeight/2, 5);
var p2:Point = new Point(triangleHeight, triangleHeight+5);
var p3:Point = new Point(0, triangleHeight+5);

//
//
//
//

var source:BitmapData = new BitmapData(triangleHeight,triangleHeight,true,0);
var bitmap:Bitmap = new Bitmap(source);

var sprite:Sprite = new Sprite();
sprite.addChild(bitmap);
addChild(sprite);


source.fillRect(source.rect,0);
source.lock();

for (var i:int = 0;i<50;i++) {
    var p:Point = getRandomPointInTriangle(p1,p2,p3);
    source.setPixel32(p.x,p.y,0xffff0000);
}

source.unlock();

Cheers!

Comments