Question

I am new to ActionScript 3.0, and am just trying to make a simple game where an instance of a MovieClip falls from the top of the screen at a random X position.

The plan: Create like 4-5 instances of the MovieClip, spawn them above the stage at random X, and have them fall. They should loop back to the top once they are off-screen, and re-randomize the X-coordinate when they do so.

The problem: I need help on the scripting, because I have pretty much no idea how to do this. I know how to make my buttons go to the scenes I want, and how to make the basket that will catch said MovieClips move along the x axis... that's about it.

Thanks!!

If I left any info out, let me know.

Was it helpful?

Solution

The first thing you need to do (in case you haven't done this yet) is to export it for ActionScript.

Step 1: Right click on your movie clip in the library. Click properties. Check the "Export for ActionScript" checkbox. If you can't see it you might need to click Advanced first. Assign a class name to your movieclip. You can leave the base class as is unless you are extending another class instance. Click OK.

Step 2: Right click on a frame in a timeline where you want to generate the movieclip. Click Actions. Assuming we named the class MyMovieClip, this block of code will add an instance of that movie clip into the stage:

var mc:MyMovieClip = new MyMovieClip() // creates a instance of the movieclip, i.e, an object
addChild(mc);                          // adds the movie clip to the upper left corner of the stage relative to the movie clip's registration point

That's basically how you add a movieclip to the stage. To add it at a random x location in the stage, you need to make use of mc's x and y fields and the Math.random() function.

Math.random() generates a pseudo-random Number n between 0 and 1 (0 <= n < 1), e.g., 0.1232... Since you might be needing a value greater or equal to 0, you will need to multiply the result to a certain integer value. Example:

var result:Number = Math.random() * 100  // returns a number between n, where 0 <= n < 100

Now since you want an x value relative to the stage, you must multiply Math.random() with the stage's width instead.

var randomX:Number = Math.random() * stage.stageWidth // returns a number between n, where 0 <= n < stage.stageWidth

Step 3: Simply set the x value of the movieclip using the pseudo-random number generated before adding it to the stage.

mc.x = randomX;

If you want it to animate by itself upon entering the stage, you will need to study event handling in AS3. See this link

Good luck!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top