Skip to main content
February 28, 2011
Question

Randomly Choosing from a List of Movie Clips.

  • February 28, 2011
  • 1 reply
  • 481 views

Hi Everyone,

I've taken a few Flash classes, but this is the first I've really been exposed to hard coding things into the stage area.

I'm working on a game, and I need to have the game randomly choose one of four movie clips to add to the stage after a given event. (ex: Mouse click)

The four movie clips are BoostUp, BoostDown, BoostLeft, and BoostRight.

I'm not really sure where to attack this from.  Any suggestions?

Thanks!

This topic has been closed for replies.

1 reply

Ned Murphy
Legend
March 1, 2011

Place the items you want to randomly select from into an array and use the Math.random() method to select one of them.

March 1, 2011

Wow, arrays are amazing, that makes sense, thank you very much.

One last thing, here is my snippet of code for the boosters, what should I be putting in the function call to make the Math.random work with the addChild(); command?

---

var boostup:MovieClip = new BoostUp();

var boostdown:MovieClip = new BoostDown();

var boostleft:MovieClip = new BoostLeft();

var boostright:MovieClip = new BoostRight();

var boostArray:Array = ["boostdown", "boostup", "boostleft", "boostright"];


stage.addEventListener(MouseEvent.CLICK, Cycle);

function Cycle(Evt:Event) :void {


}


---

Would it go:

function Cycle(Evt:Event) :void {

addChild(boostArray.Math.random();)

Or am I completely off the mark here?

Ned Murphy
Legend
March 1, 2011

Try:

function Cycle(Evt:Event) :void {

     addChild(this[boostArray[Math.floor(Math.random()*boostArray.length)]]);

}

I don't guarantee my parentheses/brackets line up properly, but I think they are okay.