How to Make The Pong Game
Code of Pong.pde:
PVector player, enemy, ball;
float ballSpeedX, ballSpeedY, enemySpeed;
int playerScore = 0;
int enemyScore = 0;
float ballSize;
void setup()
{
size(480, 320, OPENGL);
ball = new PVector(width/2, height/2);
player = new PVector(width, height/2);
enemy = new PVector(0, height/2);
ballSpeedX = width/100;
ballSpeedY = width/100;
enemySpeed = width/150;
ballSize = width/20;
rectMode(CENTER);
}
void draw()
{
background(26);
centerLine();
drawBall();
drawPlayer();
drawEnemy();
scoreText();
}
void drawBall()
{
pushMatrix();
translate(ball.x, ball.y);
fill(255);
fill(255 * (ball.x/width), 255 * ((width - ball.x)/width), 0);
noStroke();
ellipse(0, 0, width/20, width/20);
popMatrix();
ball.x += ballSpeedX;
ball.y += ballSpeedY;
ballBoundary();
}
void ballBoundary()
{
if (ball.y < 0) {
ball.y = 0;
ballSpeedY *= -1;
}
if (ball.y > height) {
ball.y = height;
ballSpeedY *= -1;
}
float playerDist = ball.dist(player);
if (ball.x > width) {
ball.x = width/2;
ballSpeedX *= -1;
enemyScore ++;
}
if (ball.x < 0) {
ball.x = width/2;
ballSpeedX *= -1;
playerScore ++;
}
if (ball.x > width - width/40 - ballSize && ball.x < width && Math.abs(ball.y - player.y) < width/10) {
ball.x = width - width/40 - ballSize;
ballSpeedX *= -1;
}
if (ball.x < width/40 + ballSize && ball.x > 0 && Math.abs(ball.y - enemy.y) < width/10) {
ball.x = width/40 + ballSize;
ballSpeedX *= -1;
}
}
void drawPlayer()
{
player.y = mouseY;
pushMatrix();
translate(player.x - width/20, player.y);
stroke(0);
fill(255);
rect(0, 0, width/20, width/5);
popMatrix();
}
void drawEnemy()
{
enemy.y += enemySpeed;
pushMatrix();
stroke(0);
translate(enemy.x + width/20, enemy.y);
fill(255, 0, 0);
rect(0, 0, width/20, width/5);
popMatrix();
enemyAI();
}
void enemyAI()
{
if (enemy.y < ball.y) {
enemySpeed = width/150;
}
if (enemy.y > ball.y) {
enemySpeed = - width/150;
}
if (enemy.y == ball.y) {
enemySpeed = 0;
}
if (ball.x > width/2) {
enemySpeed = 0;
}
}
void scoreText()
{
fill(255);
textSize(width/20);
text(enemyScore, width/10 * 3, height/5);
text(playerScore, width/10 * 7, height/5);
}
void centerLine()
{
int numberOfLines = 20;
for (int i = 0; i < numberOfLines; i++) {
strokeWeight(width/100);
stroke(255);
line(width/2, i * width/numberOfLines, width/2, (i+1) * width/numberOfLines - width/40);
stroke(0, 0);
line(width/2, (i+1) * width/numberOfLines - width/40, width/2, (i+1) * width/numberOfLines);
}
}
Comentarios
Publicar un comentario