 # [RESOLVED] Floating ball through AS?

• 04-20-2009, 11:45 PM
sandyrivers
[RESOLVED] Floating ball through AS?
Hi, I don't know why I can't seem to get my head around this, but I'm stuck before I've even begun...

What I want to do is have a MC of a ball smoothly and randomly float up,down,left and right within a 5 pixel radius of it's original x and y.

Thanks!
• 04-21-2009, 05:14 AM
Gu35s
I can make it jitter. Here.
Code:

```ball_mc.orgx = ball_mc._x; ball_mc.orgy = ball_mc._y; // yeah , orgy... ball_mc.onEnterFrame = function(){     this._x = this.orgx + (5 - Math.random()*10);     this._y = this.orgy + (5 - Math.random()*10); }```
• 04-21-2009, 10:00 AM
sandyrivers
Quote:

ball_mc.orgy = ball_mc._y; // yeah , orgy...

lol :devil:

Thanks for the code! How do I make it more relaxed and smooth and less hepped up on caffine?

Also, can you please explain this line:

(5 - Math.random()*10);

I don't understand how 5 minus a random number multiplied by 10 gives me a jittery ball. If I understood how the parameters worked, I'm sure I could tweak them to suit my needs.

Thanks!
• 04-23-2009, 05:38 AM
vinchenzison
This isn't my code but could get you started
Add a MC and call it ball (or change to whatever)
Put this in frame on main timeline

Quote:

var clip:MovieClip = ball;
var angle:Number = 90;
var distance:Number = 1;
var speed:Number = 0.05;

function motion(event:Event):void {
ball.y = ball.y + Math.sin(angle) * distance;
angle += speed;
}
• 04-23-2009, 06:24 AM
Gu35s
(5 - Math.random()*10); is just randomizing the x and y. Math.random()*10 is randomize a number up to 10 then substract by 5. meaning it should span between -5 to 5 and add that to original _x or _y then set that number as _x or _y. not moving it, but diretly setting it. that's why it's jittery. if you want movement, it's best if you do _x+= something. or just use the code vinchenzison provided. but that code is as3 so you'd have to dumb it down to as2.
• 04-23-2009, 06:52 AM
vinchenzison
Just as another tip, slightly unrelated but has saved me a lot of work in the past.

http://laco.wz.cz/tween/?page=docs/slideTo

Using these Tweening prototypes means you only have to write

mc.slideTo('xvalue', 'yvalue') to get your ball moving.

It's so simple. You could then create and array of positions and replace the x and y value with a random position from your array.

Hope that helps. I'm sure the Tweening prototypes will be of use to your furture projects if your not already using them!
• 04-23-2009, 12:50 PM
sandyrivers
Thanks to all the replied! Once I dumbed down vinchenzison code to AS2 it worked like a charm.

To anyone who does not code in AS3, here is the AS2 version:

Code:

```var angle:Number = 90; var distance:Number = 1; var speed:Number = 0.05; motion = function () {         ball._y = ball._y+Math.sin(angle)*distance;         angle += speed; }; ball.onEnterFrame = function() {         motion(); };```
Thanks everyone!