Our Flash tutorials provide you with step-by-step instructions on how to create beautiful Flash animations and integrate them into your website.  Home Flash & Swish Flash Tutorials Random Movement
Your Ad Here

Random Movement


My examples are all going to be on a stage that's 300x200, but you can work with a larger or smaller area if you wish.

You'll need to create a movieclip that will move randomly. I used a red circle.

The simplest way to make your movieclip move randomly is to add (or subtract) a random number to both the _x and _y properties of your MC. This is most easily done by like so:

onClipEvent(enterFrame){
    //random(7)-3 gives a number from -3 to 3
    _x+=random(7)-3;
    _y+=random(7)-3;
}

Test your movie and your MC should start jittering around randomly. Now, this may be far too jumpy for your taste, so lets mae it move more smoothly.

In order to make the movement smoother, we're going to reduce how frequently the MC switches directions. In order to do that, we'll set a direction variables and increment the _x and _y properties with them. We'll then test a random number to see if we should change the direction variables.

onClipEvent(load){
    xDir=random(3)-1;
    yDir=random(3)-1;
}
onClipEvent(enterFrame){
    _x+=xDir;
    _y+=yDir;
    //random(3)-1 gives a number from -1 to 1
    if (random(10) == 0){
        xDir=random(3)-1;
    }
    if (random(10) == 0){
        yDir=random(3)-1;
    }
}

When you run that, you'll notice that sometimes your MC will stop. This is because random(3)-1 returns -1, 0, or 1. When both xDir and yDir are 0, the MC pauses. If you want the MC to always be moving, you can change the code like so:

onClipEvent(load){
    xDir=1;
    yDir=1;
}
onClipEvent(enterFrame){
    _x+=xDir;
    _y+=yDir;
    //random(3)-1 gives a number from -1 to 1
    if (random(10) == 0){
        xDir*=-1;
    }
    if (random(10) == 0){
        yDir*=-1;
    }
}

The above code will flip both xDir and yDir between 1 and -1 randomly.

Obviously, you can change any of the random number generators to make your MC move more quickly. If you want a number from -n to n, the code should be random(n*2+1)-n.

This is what each of the 3 different approaches I've outlined looks like:

Source .fla (Flash 8 format)



Author's URL: FlashSandbox
Thank you for voting.
Rate this Materials:
Bad 
1 2 3 4 5 Excellent
print this page subscribe to newsletter subscribe to rss

Internet & computing Flash is a vector-based moving graphics format created by Macromedia for the publication of animations on the World Wide Web. More Flash & Swish: Most Popular Materials | Fresh Materials | More Flash Tutorials at FlashPerfection.com

Add comments to "Random Movement"

Only registered users can write comment

Reader's comments