snookian
snookian

Reputation: 873

AS3 random number

I have seen several random number question but don't undertsnad it and how I can use it. I want to generate a number between 0.5 and 2 EG 0.5,1.1, 1.2, 1.3 etc and use this in a tween. Here is what I have:

var letters:Array = [Rbox1, Rbox2, Rbox3, Rbox4, Rbox5, Rbox6,
                     Rbox7, Rbox8, Rbox9, Rbox10, Rbox11, Rbox12]

function randomRange(minNum:Number, maxNum:Number):Number
{
    return (Math.floor(Math.random() * (maxNum - minNum + 1)) + minNum);
}

start_mc.addEventListener(MouseEvent.CLICK, startAni);
function startAni(event:MouseEvent):void{
    for (var i:String in letters) {
        var letterX:int = letters[i].x;
        var letterY:int = letters[i].y - 450;
        TweenLite.to(letters[i], 1, {x:letterX, y:letterY});
    }
}

The 1 in this line becoming the random number

TweenLite.to(letters[i], 1, {x:letterX, y:letterY});

This is the speed that each of the Rbox will travel to their position:

Any help appreciated

Ian

Upvotes: 0

Views: 240

Answers (2)

WORMSS
WORMSS

Reputation: 1664

Math.random() returns 0.0 to 0.99999999 {not sure how many decimal places).

So if your random number was .23456 you then do * (2 - 0.5 + 1) brings this to 0.5864.

Math.floor() is removing your decimal places.

So then this is bring your 0.5864 to 0. You then + 0.5. Bringing it to strangely 0.5.

If you need your results to be to a 1 decimal places, as you listed, problem with the maths is the Math.floor too early. Try:

var result:Number = Math.floor(((Math.random() * (max - min)) + min) * 10) / 10;

If you require more than 1 decimal places you can turn the 10 into 100 for 2, or 1000 for 3.. If you want this to be dynamic, you can change 10 with Math.pow(10, dp); with DP being yow many decimal places you wish.

Upvotes: 0

snookian
snookian

Reputation: 873

Ok solved for randum number between 1 and 10

start_mc.addEventListener(MouseEvent.CLICK, startAni);
function startAni(event:MouseEvent):void{
    TweenLite.to(start_mc, 1, {alpha:0});
    for (var i:String in letters) {
        var letterX:int = letters[i].x;
        var letterY:int = letters[i].y - 450;

        var minLimit:uint = 1;
        var maxLimit:uint = 10;
        var range:uint = maxLimit - minLimit;
        var myNum:Number = Math.ceil(Math.random()*range) + minLimit;

        TweenLite.to(letters[i], myNum, {x:letterX, y:letterY, delay:1});
    }
}

Upvotes: 1

Related Questions