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

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

## Actionscript:

 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889 //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); }

## Source:

as3random_brownian_movement.fla

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…

 12345678910 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?

Subscribe without commenting

## Presenting at WordCamp Atlanta – Child Themes

The presentation? Your firstborn child theme. Child themes 101+2. I’m speaking at wordcamp atlanta this afternoon about themes and child themes. I’ll update this post with post-presentation notes. Learn how to mod themes the right way. Using child themes you won’t loose your edits when there’s a theme update. (101) We’ll go over the advantages [...]

## Hooks, In a Nutshell – WP Daily

I’ve published another article over on wpdaily.co exploring the concept of hooks. I remember when starting out that people kept mentioning hooks and filters and actions and… it took a while to grasp what they each meant. I think the first time I started to grasp it was when I read the codex and saw [...]

## Speaker at WordCamp Atlanta 2013

I’m excited to be speaking at WordCamp Atlanta again this year! The time is quickly approaching for WordCamp Atlanta 2013, March 15-16. I spoke last year and discussed the process of going from Photoshop PSD to WordPress Theme, here are my slides and notes for that WordCamp Presentation. This year I’m speaking along the same [...]

## WP Features: Theme or Plugin

Reading my wpdaily.co updates today and saw this post talking about WordPress theme features. Eric explains the debate: Generally-speaking, the conversations have always circled around features: There are those that believe every feature you could ever imagine should be included like text color, font selector, and more. On the flip-side, there are those that feel [...]

## Packery Preview, from Metafizzy & descended from Masonry

David Desandro / metafizzy, maker of masonry and isotope of which I’m a big fan and user of has been busy with a new project called Packery. Packery, looks to be a child of Masonry. As you would expect it seems to be pushing things much further and addressing a few pain points of masonry. [...]

## On Going Responsive (responding to Where to Start)

I needed to write this up about going responsive in response after reading Where to Start (by Trent Walton of Paravel) about getting started with responsive web design. Thanks for sharing your thoughts Trent, I agree whole heartedly. In my experience it is the same. I wanted to share his post and also add my [...]

### Evan Mullins

The keystore is used for creating valid apps that are associated with the author. It is not...

### Rohan Dave

I am new in android and have certain question about KeyStore. Is KeyStore used in user...

### arpit

very useful thank you …..

### Duan

@ugh You’re joking, right? I do some basics in Flash, but come on – all you do is...

### Cátia Vala

Thank you so much Evan! That’s great! Keep going with your amazing work.

### zproxy

thanks i bet its faster to google and find some ad hoc documentation than the other way.