Skip to content

Instantly share code, notes, and snippets.

@32bitkid
Created February 7, 2011 23:43
Show Gist options
  • Save 32bitkid/815536 to your computer and use it in GitHub Desktop.
Save 32bitkid/815536 to your computer and use it in GitHub Desktop.
package {
import flash.display.MovieClip;
import flash.events.*;
public class Ball extends MovieClip {
private const speed:Number = 5;
private var yDir:Number;
private var xDir:Number;
public function Ball() {
this.addEventListener(Event.ENTER_FRAME, update);
this.xDir = speed;
this.yDir = speed;
}
public function impact():void {
this.xDir = -this.xDir;
}
private function update(e:Event):void {
this.y = this.y + this.yDir;
this.x = this.x + this.xDir;
if (this.x < 0) {
dispatchEvent(new Event("P2_SCORE"));
this.xDir = -this.xDir;
this.x = this.stage.stageWidth / 2;
this.y = this.stage.stageHeight / 2;
} else if (this.x > this.stage.stageWidth) {
dispatchEvent(new Event("P1_SCORE"));
this.xDir = -this.xDir;
this.x = this.stage.stageWidth / 2;
this.y = this.stage.stageHeight / 2;
}
if (this.y < 0) {
this.yDir = -this.yDir;
this.y = 0;
} else if (this.y > this.stage.stageHeight) {
this.yDir = -this.yDir;
this.y = this.stage.stageHeight;
}
}
}
}
package {
import flash.display.MovieClip;
import flash.events.*;
public class PongGame extends MovieClip {
public function PongGame() {
this.addEventListener(Event.ENTER_FRAME, update);
ball.addEventListener("P1_SCORE", player1Score);
ball.addEventListener("P2_SCORE", player2Score);
}
private function player1Score(e:Event) {
trace("Player 1 has scored!!!");
}
private function player2Score(e:Event) {
trace("Player 2 has scored!!!");
}
private function update(e:Event):void {
player1.y = this.stage.mouseY;
if(player1.hitTestObject(ball)) {
ball.impact();
}
if(player2.hitTestObject(ball)) {
ball.impact();
}
if(ball.y < player2.y) {
player2.y = player2.y - 4.7;
} else if (ball.y > player2.y) {
player2.y = player2.y + 4.7;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment