Вопрос

I am pretty new to all this Flash CS6 Action script 3.0 stuff and I was hoping to find out some different ways to apply a rare drop chance on an movie clip array for AS3. I have a random chance code that works pretty well for enemies, as they fall more often, however I'd like hearts to fall rarely for my player to catch and gain a life.

Here is the code I have so far, it drops far too many hearts. I've tried fiddling with the numbers but I only seem to make it worse. Any suggestions?

function makeHeart():void
{
    var chance:Number = Math.floor(Math.random() * 60);
    if (chance <= 1 + level)
    {
        var tempHeart:MovieClip;
        tempHeart = new Heart();
        tempHeart.speed = 3;
        tempHeart.x = Math.round(Math.random() * 800);
        tempHeart.cacheAsBitmapMatrix = tempHeart.transform.concatenatedMatrix;
        tempHeart.cacheAsBitmap = true;
        trace("tempHeart");
        addChild(tempHeart);
        hearts.push(tempHeart);
    }
}
Это было полезно?

Решение

Well, this is either too simple of a question, or I just didn't understand it. If I did however understand it correctly, here's the way out:

Let's say you want to have a 1% chance of a falling heart. Since you're using a Number class for your chance variable, and Math.random() returns a Number as well, you don't need any transformations.

Math.random() returns a Number (float) between 0 and 1, not including 1

so your code for 1% could look something like this:

var chance:Number = Math.random();
if (chance <= 0.01)
{
    //enter code here
}

And yes, since you call less unneeded functions, it works faster. Math.random() gives a very precise number, far beyond 1/100, so it's possible to make a much less number for chance possibility, here's one value returned from Math.random():

Math.random(); // 0.9044877095147967
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top