Paddle and ball game needs collision detection so ball doesnt sink through paddle
I have tried copying wall collision to no avail. var canvas = document.getElementById("myCanvas"); var ctx = canvas.getContext("2d"); var ballRadius = 10; var x = canvas.width/2; var y = canvas.height-30; var dx = 2; var dy = -2; var paddleHeight = 10; var paddleWidth = 75; var paddleX = (canvas.width-paddleWidth)/2; var rightPressed = false; var leftPressed = false; //event listener for my arrow key controlls document.addEventListener("keydown", keyDownHandler, false); document.addEventListener("keyup", keyUpHandler, false); //holding finger down on arrow key function. function keyDownHandler(e){ if(e.keyCode == 39){ rightPressed = true; } else if(e.keyCode == 37){ leftPressed = true; } } //lifting finger off arrow key function function keyUpHandler(e){ if(e.keyCode == 39){ rightPressed = false; } else if(e.keyCode == 37){ leftPressed = false; } } //drawing our ball function drawBall(){ ctx.beginPath(); ctx.arc(x,y,ballRadius,0,Math.PI*2); ctx.fillStyle ="red"; ctx.fill(); ctx.stroke(); ctx.closePath(); } //drawing our paddle function drawPaddle(){ ctx.beginPath(); ctx.rect(paddleX,canvas.height-paddleHeight,paddleWidth,paddleHeight); ctx.fillStyle ="blue"; ctx.fill(); ctx.stroke(); ctx.closePath(); } //Here we display both our ball and our paddle. function draw(){ ctx.clearRect(0,0,canvas.width,canvas.height); drawBall(); drawPaddle(); //Here we add in collision detection for the left and right side walls of canvas if(x + dx > canvas.width - ballRadius || x + dx < ballRadius){ dx=-dx; } //Here we add in collision detection for the top and bottom of our canvas. if(y + dy > canvas.height - ballRadius || y + dy < ballRadius){ dy=-dy; } //right arrow key direction if(rightPressed && paddleX < canvas.width - paddleWidth){ paddleX += 7; } //left arrow key function else if(leftPressed && paddleX > 0){ paddleX -= 7; } x += dx; y += dy; } setInterval(draw, 10);