2
respostas

Dúvidas sobre bug de colisão entre bolinha, raquete e borda. PONG JS

Pessoal estou começando aqui na Alura e estou fazendo o jogo PONG com JS, HTML e CSS, conforme o curso de programação da Alura.

Eu estou me deparando com um bug de colisão entre a bolinha, raquete e borda, mesmo alterando o tamanho da raquete ou da bolinha, as vezes ocorre um comportamento inesperado em que a bolinha fica entre a borda e a face esquerda da raquete, mesmo alterando o parâmetro xRect = 0. Mesmo seguindo exatamente o que o professor passou no curso JS e tbm no Scratch, eu obtive o mesmo erro tanto no P5.JS e no Scratch. Isso ocorre mais ou menos 3% das situações, o jogo roda praticamente sem erros.

// box variables let width = 600; let height = 400;

// ball variables let xBall = width /2 ; let yBall = height / 2; let diameter = 22; let radius = diameter / 2; let xSpeedBall = 6; let ySpeedBall = 6;

// my rectangle variables let xRect = 5; let yRect = 155; let widthRect = 10; let heightRect = 90; let speedRect = 6;

// opponent rectangle variables let xRect2 = width - xRect - widthRect; let yRect2 = 155;

function setup() { createCanvas(width, height); }

function draw() { background(100); drawBall(); movementBall(); collisionBallEdge(); collisionBallRect(); drawRect(); movementRect(); drawRect2(); }

function drawBall(){ circle(xBall, yBall, diameter); }

function movementBall(){ xBall += xSpeedBall; yBall += ySpeedBall; }

function collisionBallEdge(){ if (xBall + radius > width || xBall - radius < 0){ xSpeedBall *= -1; } if (yBall + radius > height || yBall - radius < 0){ ySpeedBall *= -1; } }

function collisionBallRect(){ if (xBall - radius <= xRect + widthRect && yBall + radius >= yRect && yBall - radius <= yRect + heightRect){ xSpeedBall *= -1;} }

function drawRect(){ rect(xRect, yRect, widthRect, heightRect); }

function movementRect(){ if (keyIsDown(UP_ARROW)){ if (yRect >0){yRect -= speedRect;} } if (keyIsDown(DOWN_ARROW)){ if (yRect + heightRect < height){yRect += speedRect;} } }

function drawRect2(){ rect(xRect2, yRect2, widthRect, heightRect); }

2 respostas

Oi Felipe,

Chegou a ver as dicas nesse tópico para ver se resolve: https://cursos.alura.com.br/forum/topico-bolinha-fica-presa-na-raquete-fazendo-varios-pontos-170108 ?

Olá Rodrigo, muito obrigado por compartilhar esse artigo, não tinha visto, me ajudou aqui.

O que eu reparei é que ao utilizar o CANVAS, o movimento não é contínuo mas incremental / descontínuo. Quanto menor for o tamanho do incremento, mais próximo do real vai ficar, porém vai ficar muito lento. Ajustando o tamanho da bolinha, da raquete e da distância da raquete com a parede, esse bug diminui de fato. Mas está tudo certo, estou estudando tbm o p5.js pelo curso https://thecodingtrain.com/beginners/p5js/. Recomendo pois tem mais explicações sobre o funcionamento do p5.js.