Ultrashock Forums > Flash > ActionScript
AS3 - gaussian / weighted random distribution

You are currently viewing our website as a guest which gives you limited access to forums, files and other resources.

Click here to join now for free, and start interacting with our members, download files and much more!

Click here if you are looking for our Flash files and other professional assets.
 
Post Reply | View first unread | Rate Thread Search this Thread | Thread Tools | Display Modes

#1
Bookmark and Share!
AS3 - gaussian / weighted random distribution
Old 2009-01-09

Hi all.

I'm trying to create a weighted random distribution, and can't figure out how to go about it. basically I want to create a starry sky, where most of the stars are in the middle of the screen. by making the y random, like:

Code:
star.y =Math.random()*_mc.stage.stageHeight;
I just get an even distribution on the Y axis. What I really want is to have most of the stars near _mc.stage.stageHeight/2.

Anyone has a good idea of how to accomplish?

thanks!
::| ITAI |::
postbit arrow 2 comments | 277 views postbit arrow Reply: with Quote   
Registered User
iasseo is offline
seperator
Posts: 117
2003-02-21
iasseo lives in United States
seperator

Ultrashock Member Comments:
pixelbath pixelbath is offline pixelbath lives in United States 2009-05-29 #2 Old  
Code:
function weightMiddle(input:Number, strength:int = 2):Number {
	if (input < 0.5) return 1 - Math.pow(1 - input, strength) / 2;
	return 0.5 + Math.pow((input - 0.5) * 2, strength) / 2;
}
You may (or not) recognize this as the exploded version of the easeOutIn function from Flash's own easing equations. I only marginally tested it, but it seems to work.

Use the "strength" parameter to force it closer to middle distribution. Default value is 2, which still preserves some randomness.

You would use this function like this:

Code:
star.y = weightMiddle(Math.random()) * _mc.stage.stageHeight;
Reply With Quote  
iasseo iasseo is offline iasseo lives in United States 2009-05-29 #3 Old  
thanks! I'll give it a shot.

here's what I ended up with:

Code:
function triRand(a : Number, b : Number, u : Number):Number
{			
	var result : Number;
	var c : Number = b - ((b-a)/2);
			
	if (u <= 1){
		result = a + Math.sqrt(u * (b-a) * (c-a));
	}else{
		result = b - Math.sqrt((u-1) * (b-a) * (b-c));
	}

	return result;	
}

var a: Number = 0;
var b: Number = _mc.stage.stageHeight;
var RAN : Number = (Math.random()* 2);
var result : Number = Distribute.triRand(a, b, RAN);
Reply With Quote  
Thread Tools
Display Modes Rate This Thread
Rate This Thread: