Pong

Code Actionscript 2.0

Instance action

onClipEvent (load) {
// set speed at the beginning
speedx = 5;
speedy = 12;
}
onClipEvent (enterFrame) {
// square moves with speedx, speedy
this._x = this._x + speedx;
this._y = this._y + speedy;

// if ball leaves stage, vertical change of direction
if ((this._y > 400) || (this._y < 0)) {
trace("ping");
speedy = -1 * speedy;
}
// if square hits b2/b3, horizontal change of direction
if (this.hitTest(_parent.racket1) || this.hitTest(_parent.racket2)) {
trace("pong");
speedx = -1 * speedx;
}
}

Instance action

onClipEvent (enterFrame) {
// racket follows vertical mouse position
this._y = _root._ymouse;
}

Code Actionscript 3.0

addEventListener(Event.ENTER_FRAME,enterFrame); var speedx=5; var speedy=12; function enterFrame(event:Event) { ball.x=ball.x+speedx; ball.y=ball.y+speedy; // if ball leaves stage, vertical change of direction if ((ball.y > 400) || (ball.y < 0)) { trace("ping"); speedy=-1*speedy; } // if ball hits b2/b3, horizontal change of direction if (ball.hitTestObject(racket1) || ball.hitTestObject(racket2)) { trace("pong"); speedx=-1*speedx; } racket1.y=mouseY; racket2.y=mouseY; }

Description

A ball is hit back and forth between two rackets. This game of Pong is programmed by using the mouse position to control the rackets, while tracking the bouncing and collision of the ball.

related to: Bouncing movement, Collision, Mouse position

Download

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


Share