user1816133
user1816133

Reputation:

Action Script 3. Randomly moving items UP and DOWN from array

So I'm creating game similar like this: example

I have an array of items already added to 4 holes. I need to make that these items randomly moved up (+100px) and down(-100px).

I have added to all holes for 6 items:

    for(var i:uint = 0; i < 6; i++)
        {
        holeArr[0].inside.addChild(itemsArr[4][i]);
        holeArr[1].inside.addChild(itemsArr[5][i]);
        holeArr[2].inside.addChild(itemsArr[6][i]);
        holeArr[3].inside.addChild(itemsArr[7][i]);
        }

How can I make them randomly move up (+100px) and down(-100px)? I started, but I don't know what to do next... Could you help me, please?

function randomSpawn() {
        for(var i:uint = 0; i < 6; i++)
            {
            itemsArr[4][i].x += 100;
            itemsArr[5][i].x += 100;
            itemsArr[6][i].x += 100;
            itemsArr[7][i].x += 100;
            }
}

Upvotes: 0

Views: 88

Answers (1)

Pier
Pier

Reputation: 10817

To move an item randomly up/down +-100 pixels:

var distance = Math.round(Math.random() * 2 - 1) * 100;
mySprite.y += distance;

To animate it with Tweenlite

var newPosY = mySprite.y;
newPosY += Math.round(Math.random() * 2 - 1) * 100;
TweenLite.to(mySprite,1,{y:newPosY});

The simplest way to select a random item from an array

var index = Math.round(Math.random * (myArray.length - 1));
var myRandomItem = myArray[index];

Upvotes: 1

Related Questions