Olá Pessoal,
Conclui essa etapa do Pong com JavaScript. Como teste, inclui os nomes Player e CPU acima dos marcadores de pontos. https://editor.p5js.org/raphamass/sketches/neiIVzljn
Segue o código abaixo.
Um grande abraço a todos.
//ball variables
let xBall = 300;
let yBall = 200;
let diameter = 15;
let radius = diameter / 2;
//ball speed
let speedXBall = 6;
let speedYBall = 6;
//Player paddle variables
let xPaddle = 5;
let yPaddle = 150;
let wPaddle = 10;
let hPaddle = 90;
//CPU paddle variables
let xCpuPaddle = 585;
let yCpuPaddle = 150;
let speedYCpu;
let collision = false;
//game score
let playerScore = 0;
let CpuScore = 0;
function setup() {
createCanvas(600,400); // (width, height)
}
function draw() {
background (0);
showBall();
ballMotion();
ballEdgeCollision();
showPaddle(xPaddle, yPaddle);
paddleMotion();
//paddleCollision();
collisionPaddleLibrary(xPaddle, yPaddle); // p5.collide2D library (https://github.com/bmoren/p5.collide2D)
showPaddle(xCpuPaddle, yCpuPaddle);
paddleCpuMotion();
collisionPaddleLibrary(xCpuPaddle, yCpuPaddle);
showScore();
addScore();
}
function showBall(){
circle(xBall, yBall, diameter) // (x,y,d)
}
function ballMotion() {
xBall += speedXBall; // simpler way
yBall += speedYBall;
/* xBall = xBall + 1; where 1 = speed
xBall = xBall + speedXBall */
}
function ballEdgeCollision() {
if (xBall + radius> width || xBall - radius < 0) {
speedXBall *= -1; // "||" stands for "or"
}
if (yBall + radius > height || yBall - radius < 0) {
speedYBall *= -1;
}
}
function showPaddle(x,y) {
rect(x, y, wPaddle, hPaddle);
}
function paddleMotion(){
if (keyIsDown(UP_ARROW)){
yPaddle -= 10;
}
if (keyIsDown(DOWN_ARROW)){
yPaddle += 10;
}
}
/*function paddleCollision(){
if (xBall - radius < xPaddle + wPaddle
&& yBall - radius < yPaddle + hPaddle
&& yBall + radius > yPaddle) {
speedXBall *= -1;
}
}*/
function collisionPaddleLibrary(x,y){
collision = collideRectCircle(x,y,wPaddle,hPaddle,xBall,yBall,radius);
if (collision){
speedXBall *= -1;
}
}
function paddleCpuMotion(){
speedYCpu = yBall - yCpuPaddle - wPaddle / 2 - 30;
yCpuPaddle += speedYCpu;
}
function showScore(){
fill(255)
text(playerScore, 278, 45);
text(CpuScore, 321, 45);
text("Player", 249, 26);
text("CPU", 320, 26)
}
function addScore(){
if (xBall > 590){
playerScore += 1;
}
if (xBall < 10){
CpuScore += 1;
}
}