Bouncing movement

Code Actionscript 2.0

Instance action

onClipEvent (load) {
speedx = random(10);
speedy = random(10);
}
onClipEvent (enterFrame) {
this._x = this._x + speedx;
this._y = this._y + speedy;
if (this._x > 375) {
this._x = 375;
speedx = -speedx;
}
if (this._x < 25) {
this._x = 25;
speedx = -speedx;
}
if (this._y > 375) {
this._y = 375;
speedy = -speedy;
}
if (this._y < 25) {
this._y = 25;
speedy = -speedy;
}
}

Code Actionscript 3.0

addEventListener(Event.ENTER_FRAME,enterFrame); var speedx = int(Math.random()*10); var speedy = int(Math.random()*10); function enterFrame(event:Event) { square.x = square.x + speedx; square.y = square.y + speedy; if (square.x > 375) { square.x = 375; speedx = -speedx; } if (square.x < 25) { square.x = 25; speedx = -speedx; } if (square.y > 375) { square.y = 375; speedy = -speedy; } if (square.y < 25) { square.y = 25; speedy = -speedy; } }

Description

With this script, the square bounces from edge to edge of the stage. The position is increased by values speedx and speedy. The if-condition verifies, whether the edges of the stage has been reached. If this is the case, speedx or speedy change their direction.

related to: Back and forth

Download

Right click: Flashfile AS 2.0 | Flashfile AS 3.0 | SWF-File


Share