Games and Animation Camps
Featured Student Works :
Day & Night
Stick Fight
Pacman & Ghost
Epic Explosion
Evolution
Death Star Explosion
Code Snippets :
Pong Game
import flash.events.Event;
//variables
var ballXSpeed:Number = 10;
var ballYSpeed:Number = 10;
var enemySpeed:Number = 5;
var player_score:Number = 0;
var enemy_score:Number = 0;
//the starting functions
function start():void{
//add a listener to the paddle every frame
player.addEventListener(Event.ENTER_FRAME, movePaddle);
//add a listener to the ball every frame
ball.addEventListener(Event.ENTER_FRAME, moveBall);
//add a listener to the enemy paddle every frame
enemy.addEventListener(Event.ENTER_FRAME, moveEnemy);
}
//the move paddle function
function movePaddle(event:Event):void{
//the paddle follows the mouse
player.x = mouseX;
}
//the move enemy ai
function moveEnemy(event:Event):void{
//the enemy follows the ball
if(enemy.x < ball.x - 10){
enemy.x += enemySpeed;
}else if(enemy.x > ball.x + 10){
enemy.x -= enemySpeed;
}
//with a slight margin of error
}
//the move ball function
function moveBall(event:Event):void{
//check if ball hits paddle
if(ball.hitTestObject(player)){
calcBallAngle();
}
//check if ball hits enemy
if(ball.hitTestObject(enemy)){
calcBallAngle();
}
//bouncing the ball off the walls
if(ball.x >= stage.stageWidth-ball.width){
ballXSpeed *= -1;
}
if(ball.x <= 0){
ballXSpeed *= -1;
}
if(ball.y >= stage.stageHeight-ball.height){
//ballYSpeed *= -1;
enemy_score++;
ballXSpeed = -10;
ballYSpeed = -10;
}
if(ball.y <= 0){
//ballYSpeed *= -1;
player_score++;
ballXSpeed = 10;
ballYSpeed = 10;
}
//update position by speed
ball.x += ballXSpeed;
ball.y += ballYSpeed;
//update score
playerScore.text = "Score: " + player_score;
enemyScore.text = "Score: " + enemy_score;
}
//the function to calculate ball angles
function calcBallAngle():void{
//lets grab the position of the ball on the paddle
var ballPos:Number = ball.x - player.x;
var hitPercent:Number = (ballPos / (player.width - ball.width)) - .5;
ballXSpeed = hitPercent * 5;
ballYSpeed *= -1;
}
//start the code
start();