Random Movement | Brownian revisited for as3

I have had feedback that certain random movements I program are a bit “jumpy”. Such as my old brownian movement tutorial and I really noticed it in my last tutorial, the parallax 3d depth effect tutorial. I’ve been thinking about it and looking around at some code and now have this updated brownian movement example! Updated for as3 as well as making it less jumpy.

as3brownian thumb pngFirst I’ll explain what I’ve found to be the reason of the jumpiness. And then explain and show what can be done to make this movement be more smooth.

So to examine the old jumpy code. Jump back to the first version post here. I think my technique was well thought out here, but the application was poor. It was recalculating the velocities every single frame and then incrementing the coordinate positions by the newly calculated velocities… This is where the jumpiness comes in. Even though the random value was named velocity, it didn’t actually affect the dot’s velocity, it was just a variable that stored the random value used to move the current x/y coordinates.
To help the animation be more smooth, the velocity needs to be more smooth. The velocity, rather than calculating it fresh each frame, should be randomly modified each frame. And then the new velocity will calculate the new ‘random’ position. Another addition is to introduce another force to dampen the velocity over time, so things don’t get too crazy…

Steps:

  1. Modify velocity randomly
  2. With velocity and current position, calculate a new position
  3. Dampen the velocity

Example:

Here I have a velocity for the x coordinate as well as the y. I’m also experimenting with a z velocity. This adjusts the alpha and scale for depth perception. It doesn’t actually edit the depth or layer the dot shows up on the stage however… keyword here: experimenting. :)

Get Adobe Flash player

Actionscript:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
//number of balls
var numBalls:uint = 50;
var defaultBallSize:uint = 30;

//init
makeDots();

function makeDots():void {
    //create desired number of balls
    for (var ballNum:uint=0; ballNum<numBalls; ballNum++){
        var c1:Number = randomColor();
        var c2:Number = randomColor();

        //create ball
        var thisBall:MovieClip = new MovieClip();
        thisBall.graphics.beginFill(c1, .9);
        thisBall.graphics.lineStyle(defaultBallSize/3, c2, .9);
        thisBall.graphics.drawCircle(defaultBallSize, defaultBallSize, defaultBallSize);
        thisBall.graphics.endFill();

        addChild(thisBall);

        //coordinates
        thisBall.x = Math.random() * stage.stageWidth;
        thisBall.y = Math.random() * stage.stageHeight;
        //percieved depth
        thisBall.ballNum = ballNum;
        thisBall.depth = ballNum/numBalls;
        thisBall.scaleY = thisBall.scaleX = thisBall.alpha = ballNum/numBalls;
        //velocity
        thisBall.vx = 0;
        thisBall.vy = 0;
        thisBall.vz = 0;

        //ball animation
        thisBall.addEventListener(Event.ENTER_FRAME, animateBall);
    }
}

var dampen:Number = 0.95;
var maxScale:Number = 1.3;
var minScale:Number = .3;
var maxAlpha:Number = 1.3;
var minAlpha:Number = .3;
function animateBall(e:Event):void{
    var thisBall:Object = e.target;
    //apply randomness to velocity
    thisBall.vx += Math.random() * 0.2 - 0.1;
    thisBall.vy += Math.random() * 0.2 - 0.1;
    thisBall.vz += Math.random() * 0.002 - 0.001;

    thisBall.x += thisBall.vx;
    thisBall.y += thisBall.vy;
    thisBall.scaleX = thisBall.scaleY += thisBall.vz;
    thisBall.alpha += thisBall.vz;
    thisBall.vx *= dampen;
    thisBall.vy *= dampen;
    thisBall.vz *= dampen;

    if(thisBall.x > stage.stageWidth) {
        thisBall.x = 0 - thisBall.width;
    }
    else if(thisBall.x < 0 - thisBall.width) {
        thisBall.x = stage.stageWidth;
    }
    if(thisBall.y > stage.stageHeight) {
        thisBall.y = 0 - thisBall.height;
    }
    else if(thisBall.y < 0 - thisBall.height) {
        thisBall.y = stage.stageHeight;
    }

    if (thisBall.scaleX > maxScale){
        thisBall.scaleX = thisBall.scaleY = maxScale;
    }
    else if (thisBall.scaleX < minScale){
        thisBall.scaleX = thisBall.scaleY = minScale;
    }
    if (thisBall.alpha > maxAlpha){
        thisBall.alpha = maxAlpha;
    }
    else if (thisBall.alpha < minAlpha){
        thisBall.alpha = minAlpha;
    }
}

function randomColor():Number{
    return Math.floor(Math.random() * 16777215);
}

Source:

as3random_brownian_movement.fla

This entry was posted in tutorial and tagged , , , , , , , , , , , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

32 Comments

  1. Posted February 12, 2009 at 10:48 am | Permalink

    Just what I am looking for! I just need menu items (words) to slide down the screen with changing speeds (so just on the Y axis). I am use to using the timeline (now with flash cs4) but I never now how to incorporate actionscript into my motion tween or visa versa so I always get confused about this.

  2. Fluke32
    Posted March 10, 2009 at 9:11 pm | Permalink

    Hi, your work was wonderful! I tinkered with it and was able to make the balls move around instead of just float!:D Anyway, I was wondering… Have you tried animating a bitmap image instead of making graphics manually?

    I’ve tried to work on your fla file and applied the use of loaders, but it still doesn’t work quite as how I thought it would. It only adds 1 instance of the image, which quite frankly isn’t enough IMO.-_-;

  3. Posted March 11, 2009 at 10:21 am | Permalink

    @Fluke – yes, there are a few different ways to do this, you can load an external image or include it in the library. I was just using the drawing api here for simplicity, I’m showing how to code for random movement, and using bitmaps would be extra code to confuse people… ;)

    Make sure you load it for every instance you need.

  4. Ash
    Posted March 26, 2009 at 3:32 pm | Permalink

    Hi, This is awesome! If I want to add a Stop button for the user to stop the animation, what script would I use? Sorry, I’m a beginner and am just learning. :)

  5. Posted March 26, 2009 at 4:15 pm | Permalink

    @Ash – I would wrap the contents of the animateBall function with a conditional that looks at a boolean that can be set to false when the stop button is clicked. Something like this…

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    var stopPressed:Boolean = false;
    stopButton.addEventListener(MouseEvent.CLICK, clickStop)
    function clickStop(e:MouseEvent):void{
       stopPressed = true;
    }
    function animateBall(e:Event):void{
       if (!stopPressed){
          //current content
       }
    }

    Let me know how it works for you.

  6. Steve
    Posted April 24, 2009 at 3:07 pm | Permalink

    I’ve been having problems with bit maps not moving with sub pixel precision. So I though I would alter this code, substitute bitmaps for the generated circles, and see if your smooth motion worked. Sure enough, no sub pixel sampling.
    You mentioned that you could do this with bitmaps, but I wondered if you had tried, and what success you had with smooth movement.
    Is there a trick to getting flash to position objects that are not “drawn” but picture based with accuracy less than 1 pixel? What’s happening for me is that the bitmap stays still until the position decimal values kick over to the next integer value then the bitmap is moved to the next whole pixel. This is not apparent with fast moving objects or objects being dragged by the mouse, but with subtle movement like this it’s pretty jerky. (I even took out the scaling to try and get a smoother look).
    Thoughts?

  7. Steve
    Posted April 24, 2009 at 5:26 pm | Permalink

    I have tried both of those. Perhaps I am not implementing them properly, but I get no errors thrown except where outlined below.
    I’ve reorganized the code so that the function that loads the circles on to the stage(in my case little bitmaps), is in a document class .as file. Then the code that moves the bitmaps around is in a separate class .as file that is called from the document class function. This all works, I even get perfectly smooth motion if instead I have flash draw circles or even make a movie clip of a runtime-drawn circle and move those – an that’s with the pixel snap and stage quality at default. But when it’s an image it’s pretty choppy resulting from decimal increments to the x and y.

    So I have
    StageQuality.BEST;
    PixelSnapping.NEVER;
    sitting in my document class right before the document class function.

    I have tried the myBitMap.smoothing =true; in a number of places but I keep getting errors. I have tried it in the function that places them on the stage using it’s variable name, and I have tried it inside the function that moves them around using this.smoothing=true;
    To be fair I have my image object extending a movie clip as I plan to have elements inside it animating as well. The “bitmap” I’m using is classed as movie clip in the library. So perhaps I can’t attach the smoothing function to a MovieClip? Must I use bitMaps alone to get a smooth motion?
    Is this just my AS2 gene asserting itself again? (really, I thought I had evolved!)
    Thanks

  8. Steve
    Posted April 24, 2009 at 5:29 pm | Permalink

    I had a thought – am I missing an import that would allow this?
    I am only importing display* and events* at this point

  9. Steve
    Posted April 24, 2009 at 5:42 pm | Permalink

    I think it might be a limitation of Flash – although I don’t remember having this problem before and we do this kind of thing a lot. Take a look at the Interactive Image Viewer with Physics to the right on this page in the FlashDen files. The circles that mask the little images are moving smoothly, but the image inside is jumping all over the place as it aligns with whole pixels.
    Is there a way to do this with the DisplacementMap filter? It seems to be able to smoothly move pixels of a bitmap around in very small increments. Or am I just missing something that is going to make me stamp QWERTY into my forehead in reverse?
    Cheers.

  10. jeff
    Posted July 8, 2009 at 3:26 pm | Permalink

    Very great work. thank you. what would be the code to have it draw more random and organic shapes. (not circles)

    thanks

  11. Sam
    Posted September 29, 2009 at 10:08 pm | Permalink

    This is really cool and just what I need, but I was wondering how exactly I would get to load a bitmap instead of the graphic or even a button. I really want this kind of movement for a set of nav bar buttons I’m working on but I just can’t figure it out.

    Cheers

  12. Phil
    Posted October 21, 2009 at 6:02 pm | Permalink

    Gotta say..looks wicked.

    Is there anyway that the cells can resize with the browser window?

    I’ve had a go but with no success

    Cheers

  13. Posted November 4, 2009 at 11:19 pm | Permalink

    thank you for sharing this – and explaining it! i’ll be sharing this (along with the older version) with my students as we get into algorithmic art and chance.

  14. James
    Posted January 22, 2010 at 11:00 am | Permalink

    It looks like after some time majority of the balls get dragged to the upper left corner. In older version all the balls get there pretty fast and stay there. It seems that this movement has a pattern after all. Probably Math.random() fault?

  15. Posted March 1, 2010 at 4:23 pm | Permalink

    Thanks for the great idea and clear tutorial. I used your code as starting point and tried if I could make some random fireflies with it. This is the first quick try I managed to build in a sort of rally on mouseclick, they kinda twirl casually towards the latest mouseclick. Needs some tweaking here and there, but I’ll get there. A great thank you for providing me with the means to experiment with this!

  16. Alex
    Posted July 29, 2010 at 9:24 pm | Permalink

    Hi, Thax for the AS it works great, but i want to load a instance from library, how can i do?, I´m a begginer in AS3.

    Thank u for all and best regards.

    • Posted August 2, 2010 at 9:28 am | Permalink

      @Alex – You’ll need to check the box “Export for Actionscript” in the property for that instance in the library and you should be able to create that instance by name in your code.

  17. Aj
    Posted August 11, 2010 at 9:30 pm | Permalink

    Hello,

    How do you keep the color the same…i.e all the balls the same color like red.

    Cheers,

    AJ

  18. Aj
    Posted August 11, 2010 at 9:31 pm | Permalink

    …or all the balls in the same color scheme. For example, red, light red, dark red (maybe pink) etc…

  19. Almog Koren
    Posted August 12, 2010 at 6:26 am | Permalink

    Hi this is great I’m trying to do this inside a movieclip and have my balls stay inside of any ideas on what I need to adjust?

    Thanks,
    Almog

    • Posted August 13, 2010 at 10:40 am | Permalink

      @Almog,

      You want to have a container movie clip to enclose these balls? Add them to that specific movie clip in line 21, and update the limits I have now that are for the stage. Update them to be the movie clip limits. Let me know if that makes sense or if I totally misunderstood your question.

      Nice site by the way, I really enjoyed your reel!

  20. Posted August 13, 2010 at 10:55 am | Permalink

    @Evan, thanks for getting back to me and the feedback on the demo reel.

    this would be correct ?

    if(thisBall.x > containerClip.width) {
    thisBall.x = 0 – thisBall.width;
    }
    else if(thisBall.x containerClip.height) {
    thisBall.y = 0 – thisBall.height;
    }
    else if(thisBall.y < 0 – thisBall.height) {
    thisBall.y = containerClip.height;
    }

    Thanks,
    Almog

    • Posted August 13, 2010 at 12:26 pm | Permalink

      @Almog, right that’s where I would start at least. Depending on the “globalness” of the coordinates on thisBall, but I think they are calculated from within the stage of the containerClip so it should work like a charm. If not, may need to do some calculations iwth the x and y coords. Best of luck!

  21. Posted September 1, 2010 at 8:35 am | Permalink

    Hi, nice script, i am testing it right now. Is there a way to prevent them from floating to the upper left corner?

    • Posted September 3, 2010 at 1:21 pm | Permalink

      @dion – I’m sure there is, I’ve never taken the minute to figure it out, I suppose it’s something to do with the fact that the “random” numbers generated for the coordinate translation are skewed to the negative slightly. Which would move them eventually to the negative x and y coordinates. Let us know if you find it!

  22. Posted May 18, 2011 at 10:44 pm | Permalink

    Nice! Thanks for sharing. The motion looks beautiful. I was looking for something to give my space ferrying orb creatures some natural movement. This works as a great reference. I’ll post a link and will also link in my work if I finish something. :)

  23. Posted December 13, 2011 at 2:43 pm | Permalink

    Just wanted to say thanks for sharing your code for this. I was building something where I wanted to recreate the random bokeh effect that has grown popular in backgrounds. I replaced the randomColor function with a function to generate random blur amounts that I applied at the end of the dot creation section. Then I set the colors to one static color slightly brighter than my background to keep colors simple and inline with a look the client had been using in their print adverts. Worked out well.

  24. Jacky
    Posted December 14, 2011 at 10:37 am | Permalink

    It’s cool. I’m a new user for CS5. May I know is there anywhere to change it to star shape? Thanks.

  25. daibot
    Posted December 14, 2012 at 10:47 am | Permalink

    Just found this, total AS3 newbie. How do I attach bitmaps to replace the drawn circles? Anyone help please?

  26. kwan
    Posted December 21, 2012 at 1:38 pm | Permalink

    how do you remove all the childre of the balls?

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes <a href="" title="" rel=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

  • Recent Posts

    custom post types wordcamp presentation evan mullins

    WordCamp Presentation on WordPress.TV

    My presentation about Custom Post Types and Custom Fields from WordCamp Atlanta 2014 has been added to wordpress.tv. Here it is! Enjoy! Tweet

    WCATL-Speaker

    Custom Post Types or Choose Your Own Adventure – WordCamp Atlanta 2014

    I’ve been fortunate enough to be able to present at WordCamp Atlanta 2014. That makes the 3rd year in a row I’ve been able to contribute to WordCamp Atlanta! Here are my slides. I’ll be posting a full blown post of my presentation as soon as I can get it all down. Plus I hear […]

    Screenshot 2014-03-17 08.12.14

    What screens want

    Great read if you haven’t yet read it yet: Frank Chimero : What screens want : http://frankchimero.com/what-screens-want/ web and interaction design are just as much children of filmmaking as they are of graphic design. Maybe even more so. After all, we both work on screens, and manage time, movement, and most importantly, change. So what […]

    bed-bug-lifecycle-stages

    Before You Report that Bug, Use this Pre-Contact, Self-Diagnosis Routine

    Wisdom for bug reporting from Newfangled There are a few things a developer usually needs to know in order to diagnose a bug, and these are the things we’re likely to come back and ask you about if you haven’t already provided them. So, to ensure we can help you as quickly as possible, here’s […]

    deathtozach-06

    In dependence – Not dead

    Great summary and call to arms to write our own content in our own ways on our own sites. Call it what you like but ‘blogging’ is somewhat waning, in the social webs. Since as easy it is to create your own site and express your own voice, we’re flocking to the ‘services’ that will […]

    Screenshot 2014-03-17 08.50.27

    I ain’t ‘fraida no maths

    I’d heard of the ‘coding maths’ series, but hadn’t watched it yet. I should have, it’s great! Keith Peters (one of the people who first got me into scripting) has a great series about the math behind coding and as always he has a way of making complex things simple to me! Learn all you […]

css.php