Since this effect can be somewhat tricky to work out from scratch , I thought it would be helpful to publish for others to see. The trick is to employ circular motion (yes, trig functions) to make sure the bubble returns to its original spot and doesn’t slowly float away, yet make the motion appear to not be perfectly circular.

The function to start a movie clip floating, including variables for the range of motion in the X and Y directions, the speed at which the movie clip can move in those ranges, and the decay of that motion. Set the decay from .01 to .09 to determine how fast it the motion will decelerate, or set it to 1 to continue floating indefinitely.

```function makeFloat (movieClip, xDist, yDist, xSpeed, ySpeed, decay){ movieClip.xDist = xDist; // Horizontal range in pixels movieClip.yDist = yDist; // Vertical range in pixels movieClip.xSpeed = xSpeed;// Horizontal speed in radians movieClip.ySpeed = ySpeed;// Vertical speed movieClip.decay = decay; // Decay rate of motion (.01 to .99, or 1 for no decay) if(movieClip.startX == undefined){ movieClip.startX = movieClip._x; movieClip.startY = movieClip._y; movieClip.xRad = 0; movieClip.yRad = 0; } movieClip.onEnterFrame = float; } ```

The float function:

```function float(){ with(this){ xDist*=decay; yDist*=decay; xRad += xSpeed; yRad += ySpeed; _x = startX + Math.sin (xRad+=.05)*xDist; _y = startY + Math.sin (yRad+=.025)*yDist; if(Math.abs(xDist)<.2 && Math.abs(yDist)<.2){ onEnterFrame = null; } } } ```

And of course, to begin floating a movie clip, use the following code (_root makes it work from anywhere in the file).

```_root.makeFloat (floating_bubble, 35, 25, .005, .005, 1); ```

If you want to be really slick, there are two potential additions to this algorithm. First, an “acceleration” part to vary the randomness of the floating (beyond what is already there). Second, a similar function can be employed to control the rotation of the bubble, again ensuring that it returns to it's original rotation and doesn't begin spinning out of control. The timing of the rotation can be such that it is out of sync with the floating, and thus appears to be more random.

Sphere: Related Content