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. ๐Ÿ™‚
[kml_flashembed fversion=”8.0.0″ movie=”https://circlecube.com/circlecube/wp-content/uploads/sites/10/2009/02/as3random_brownian_movement.swf” targetclass=”flashmovie” publishmethod=”dynamic” width=”550″ height=”550″ wmode=”transparent”]

Get Adobe Flash player

[/kml_flashembed]

Actionscript:

[cc lang=”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 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); } [/cc]

Source:

as3random_brownian_movement.fla

33 thoughts on “Random Movement | Brownian revisited for as3

  1. 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. 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. @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. 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. @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…

    [cc lang=”actionscript”]
    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
    }
    }
    [/cc]

    Let me know how it works for you.

  6. 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. 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. I had a thought – am I missing an import that would allow this?
    I am only importing display* and events* at this point

  9. 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. Very great work. thank you. what would be the code to have it draw more random and organic shapes. (not circles)

    thanks

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

    thanks

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

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

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

  15. 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?

  16. 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!

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

    1. @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.

  18. Hello,

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

    Cheers,

    AJ

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

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

    1. @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!

  21. @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

    1. @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!

    1. @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. 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. 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. It’s cool. I’m a new user for CS5. May I know is there anywhere to change it to star shape? Thanks.

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

Comments are closed.