I'm currently building an very simplified version of the Atari breakout game. After running this bit of code for around 5 seconds(after the ball makes around 3 loops around the board), the ball gets stuck in the right wall and does a weird jittery jumping motion. When I change the width/height properties of the ball or the board or any other element, it works fine. I'm just confused as to why this would be occurring. Here's the code:
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var x =
var y = canvas.height-30;
var dx = 2;
var dy = -2;
var ballRadius = 10;
function drawBall() {
ctx.beginPath()
ctx.arc(x, y, ballRadius, 0 , Math.PI*2);
ctx.fillStyle = "rgba(0, 0, 255, 0.8)";
ctx.fill();
ctx.closePath();
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawBall();
drawPaddle();
x += dx;
y += dy;
if ((y + dy < ballRadius) || (y + dy > canvas.height - ballRadius)) {
dy = -dy;
}
if ((x + dx < ballRadius) || (x + dy > canvas.width - ballRadius)) {
dx = -dx;
}
}
setInterval(draw, 10);
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<title>Atari Breakout</title>
<link rel='stylesheet' href='breakout.css'>
</head>
<body>
<canvas id='myCanvas' width='480' height='320'></canvas>
</body>
</html>
The code isn't that clean, but I don't understand why the ball gets stuck in the right wall after ~ 6seconds?