This is an example I made playing with Sin Waves to create a random floating motion.
The formula I used breaks down like this:
this._x = MiddlePosition + Math.sin(angle) * RangeAmount;
angle += speed;
What this does is it gives me a range of motion that continually loops. For example, if my MiddlePosition(Starting Point) is 0, and I give a RangeAmount of 50 pixels and apply the formula above to the clips _x onEnterFrame, it will count up to 50, then count down to -50, the back to 50 and so on. This is nice for creating simple bobbing, floating, or just any type of ambient motion.
It's funny, I remember telling my high school algebra teacher I would never in my life use sine or cosine, now I'm geeking out over it.
import flash.display.BitmapData;
// ranges (X range, Y range, Rotation range, Xscale range, Yscale range) var ranges:Array = new Array (5, 5, 10, 7, 7); // create clips var clip:MovieClip = this.createEmptyMovieClip("clip", 1); // load bitmap var bmp = clip.createEmptyMovieClip("bmp_mc", 1); var bmpObj = BitmapData.loadBitmap("mh"); bmp.attachBitmap(bmpObj, 2, "auto", true); // position it clip._x = 50 + ranges[0]; clip._y = (Stage.height/2) - (clip._height/2); /* ------------------------------------------------------------------------------------------------ Floaties Function --------------------------------------------------------------------------------------------- */ function floaties (clip:MovieClip) { // angles bmp.ax = 0; mp.ay = 0; bmp.ar = 0; bmp.axs = 0; bmp.ays = 0; // velocities bmp.vx = .05 + (Math.random() * .05); // xspeed bmp.vy = .05 + (Math.random() * .05); // yspeed bmp.vr = .03 + (Math.random() * .03); // rotation speed bmp.vxs = .03 + (Math.random() * .03); // xscale speed bmp.vys = .03 + (Math.random() * .03); // yscale speed // init position bmp.centerX = bmp._x; bmp.centerY = bmp._y; bmp.onEnterFrame = render; } /* ------------------------------------------------------------------------------------------------ render --------------------------------------------------------------------------------------------- */ render = function() { // adjust properties this._x = this.centerX + Math.sin(this.ax) * ranges[0]; this._y = this.centerY + Math.sin(this.ay) * ranges[1]; this._rotation = 0 + Math.sin(this.ar) * ranges[2]; this._xscale = 100 + Math.sin(this.axs) * ranges[3]; this._yscale = 100 + Math.sin(this.ays) * ranges[4]; // adjust angles this.ax += this.vx; this.ay += this.vy; this.ar += this.vr; this.axs += this.vxs; this.ays += this.vys; } /* ------------------------------------------------------------------------------------------------ Make it Float --------------------------------------------------------------------------------------------- */ floaties (clip); stop();
Leave a Reply