Brownian Movement in Actionscript | Random Motion Tutorial
Overview
Having things drift around or move randomly has always interested me. Having an animation that is never going to be the exact same thing is very exciting. The focus turns from key-ing exact animations to programming a feel and letting the animations take car of themselves! One type of seemingly random motion is Brownian motion. This gives the movement a random walk wandering look, it will just drift around with no real direction.
Steps
Step by step this process is very simple. In every random motion you create the random number, and apply it to the property. If you want constant random action (motion) rather than just random placement, you repeat that over and over.
- Make a random number (random velocity)
- Apply the random number (apply velocity to property)
- Repeat (if needed)
To create a random number in actionscript, use Math.random(), which creates a random number between 0 and 1. Usually you’ll want to scale it to a range you want to use. If you want a number between 50 and 100, you’d do Math.random() * 50 + 50. *50 to scale it to 0-50, and + 50 to bring it up to 50 – 100. Also if we want to get a 100 range around 0 (-50 – 50) we would do Math.random() * 100 – 50. In the code below I’ve abstracted this to Math.random() * this.randomRange – this.randomRange/2.
Example
Here I’ve got dots created and placed randomly, with randomly set scale and alpha. On every frame each dot has a random velocity applied to it’s x and y coordinates.
The yellow dot is the simple example (code below) and the rest are included in the complex example below.
Actionscript
Simple Example:
1 2 3 4 5 6 7 8 | dotOne.onEnterFrame = function() { //create a random velocity for x and y direction vx = Math.random() * 4 - 2; vy = Math.random() * 4 - 2; //apply velocity to coordinates this._x += vx; this._y += vy; } |
Complex example:
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 | var numDots = 25; var randomRange = 1; for(var i=1; i<=numDots; i++) { //create a new dot duplicateMovieClip(_root.dot, "dot"+i, i); //save it's ref path for use theDot = _root["dot"+i]; //give it random coordinates theDot._y = Math.random() * Stage.height; theDot._x = Math.random() * Stage.width; //give each dot a distinct random range theDot.randomRange = i/numDots; //give each dot a random size and transparency theDot._xscale = theDot._yscale = theDot._alpha = i*4; //apply this code on the dot every frame theDot.onEnterFrame = function() { //create a random velocity for x and y direction within the specifically created random range for each dot vx = Math.random() * this.randomRange - this.randomRange/2; vy = Math.random() * this.randomRange - this.randomRange/2; //apply velocity to coordinates this._x += vx; this._y += vy; } } |





































