I have created my first ping-pong game with JavaScript and Canvas. I will be glad if anybody can tell me how to optimize the code and functionality.
https://github.com/nikitalarionov/js-pong
First collision detection:
//Function to check collision between ball and one of
//the paddles
function collides(b, p) {
if(b.x + ball.r >= p.x + p.w && b.x - ball.r <= p.x + p.w) {
if (b.y + b.r >= p.y && b.y + b.r <= p.y + p.h && b.x - b.r <= p.x) {
paddleHit = 1;
if(b.x < W/ 2) {
hit++;
} else if (b.x > W / 2) {
hit2++;
}
return true;
}
else if(b.y - b.r <= p.y && b.y - b.r >= p.y - p.h && b.x + b.r >= p.x) {
paddleHit = 2;
if(b.x < W/ 2) {
hit++;
} else if (b.x > W / 2) {
hit2++;
}
return true;
}
else return false;
}
}
I experience bad performance when the ball hits an angle of one of the paddles:
// Function that updates everything, score, positions, main game logic
function update(){
// Move the padles
for(var i = 0; i <= padles.length; i++) {
var p = padles[i];
if (i === 0 && players[0].moveUp) {
if (p.y <= 0) {
p.y = 0;
}
else {
// is it how i move left paddle
// it is doesn't work good like a mousemove
// animations is slowly, i dont know how to fix it
p.y -=25;
}
}
if (i === 0 && players[0].moveDown) {
if (p.y + p.h >= H) {
p.y = H - p.h;
}
else {
p.y += 25;
}
}
if (mouse.y && i === 1) {
if (p.y + p.h >= H && mouse.y > p.y) {
p.y = H - p.h;
}
else {
p.y = (mouse.y -50) - p.w / 10;
}
}
}
// ... some code
}
There I have very lazy animation and moving of the left paddle. I use keys for it outside of the animation cycle:
// Add Global Event to handle keyboards buttons
window.addEventListener('keydown', function(e) {
if (e.keyCode === 87) {
players[0].moveUp = true;
} else
if (e.keyCode === 83) {
players[0].moveDown = true;
}
}, false);
window.addEventListener('keyup', function(e) {
if (e.keyCode === 87) {
players[0].moveUp = false;
} else
if (e.keyCode === 83) {
players[0].moveDown = false;
}
}, false);