# choose randomly

## Recommended Posts

im trying to chose randomly from my array

balls.enableBody = true;

var l = ['greenb1' , 'greenb2' ,'greenb3' ,'greenb4' , 'redb1' ,'redb2' , 'blueb2', 'blueb2' , 'blueb3' ,'blueb4' , 'yellowb1' , 'yellowb2' , 'orangeb1' ,'orangeb2'] ;
for(var i = 0 ; i<(10 + Math.random() * 40) ; i++){

var s = aliens.create(game.world.randomX, game.world.randomY, l[Math.floor(Math.random() * myShows.length)]);

s.name = 'ball' + s;
s.body.collideWorldBounds = false;
s.body.bounce.setTo(1, 1);
s.body.velocity.setTo(10 + Math.random() * 40, 10 + Math.random() * 40);

}

##### Share on other sites

What's the problem exactly? Do you not know how to pick randomly from an array? I'm not sure what you're trying to do with the whole (10 + Math.random() * 40) operation. The simplest thing to do as far as getting a random array index would be to write "var index = Math.floor(Math.random() * myArray.length);".

##### Share on other sites

4 hours ago, mohammed alsaqqal said:

for(var i = 0 ; i<(10 + Math.random() * 40) ; i++){

Move the computation out of the for loop's comparison, as Math.random() will pick a different random number each time the loop iterates and the comparison is made.

##### Share on other sites

``````var s = aliens.create(
game.world.randomX,
game.world.randomY,
Phaser.ArrayUtils.getRandomItem(l) // ...et voilà!
);``````