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:

    //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.

    30 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…

      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.

    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

      WordPress updates plugin directory

      New additions to the plugin directory include: favorites, incorporating support forums into it's own tab for each plugin as well as support stats being displayed! Great! I think we also need the ability to give plugins ratings and reviews (bonus points if it can be done from within a wordpress admin dashboard when installing plugins). [...]

      Short Head

      Use zipf's short head to tune your website rather than redesign the whole thing. To make a website successful it needs to meet the needs of the users. Find out what those needs are by using the short head philosophy to equate most searched things as the biggest needs of the users. Use personas to [...]

      Img Set?

      Great article at a list apart discusing the state of the industry regarding responsive images. This picks apart the set attribute of the img element from a surprisingly objective view coming from someone so close to the picture element. Insightful discussion about the principle behind the proposals than the actual solution too. If the working [...]

      Triudo

      A mesmerizing animated triangle-ish shape form. Embedded Link triduo triduo Tweet

      Git – the paradigm shift

      A great developer story about the differences on what Git is vs other version control and what Git is not. This is how we should learn it. I heard over and over that it was distributed, but never grasped what that meant, so here are a few links and explanations that will help unlearn version [...]

      Tweening Lib comes to Javascript!

      I'm very excited to share the news that the tween library from GreenSock (hands down the best tweening library I used in flash) is not ported for use in javascript! This will be great! I missed that simple syntax from as3 when animating javascript, and now I can have my cake and eat it too. [...]

      Responsive CSS Tricks

      Here are a few useful css tricks to remember when building responsive design sites from web designer wall Embedded Link 5 Useful CSS Tricks for Responsive Design Making the design to be responsive is very easy as shown in my Responsive Design in 3 Steps tutorial, but maintaining the elements to look aesthetically balanced on [...]

      Picture element of srcset attribute?

      Bruce details the reasons and story behind the srcset attribute which is now introduced as an alternative to the picture element. Some aspects of the attribute are nice (like the fact that it's an attribute and not a new element, so it's creating up new elements with for problems. It's adapting currently used elements to [...]

      SVG Preloader with Raphael JS

      Here's a very creative use of using a newly available technology. Using svg graphics which are very lightweight, for a website preloader. I like the animation used as well. Embedded Link Make a stylish preloader with SVG | Tutorial | .net magazine Many sites neglect users with slow connections. Ian Culshaw explains how to use [...]

      CSS3 Button/Icon set

      I've been secretly hoping to see a few of these pop up once the whole icon font idea spread through the nets. I really like this idea and it's a very nice implementation too! I only see some quality issues on a couple of the icons (such as youtube), but it's awesome and I hope [...]

    • Recent Comments

      Bruce Brownlee

      Bruce Brownlee

      Ah IE6. I'd have 2 more years of sleep without IE6. Margin doubling, no properties,...
      versaena

      versaena

      how to give color at runtime…… thank you
      Mobile Websites

      Mobile Websites

      I disagree, mobile websites are the future – desktop websites and mobile websites...
      Matt Fasick

      Matt Fasick

      That's cool. I like the ripple effect as well.
      Nico

      Nico

      hi! really great job guy! very impressive.. just a question… do u have a solution to do a refresh...
      Evan Mullins

      Evan Mullins

      Agreed! I've just seen some people get pretty heated about separating all functionality...