let xBall = 0; let yBall = 0; let speedXBall = 2; let speedYBall = 2; let xPaddle = 0; let yPaddle = 600; let speedXPaddle = 20; let isCollision = false; let rndX = 1; let rndY = 1; function fun(){ let divBall = document.getElementById("divBall"); let divPaddle = document.getElementById("divPaddle"); id = setInterval(frame, 10); function frame(){ isCollision = checkCollision(divBall, divPaddle) if (!isCollision){ divBall.style.left = xBall + "px"; divBall.style.top = yBall + "px"; xBall += rndX * speedXBall; yBall += rndY * speedYBall; }else{ rndX = Math.floor(Math.random() * 3) + 1; rndY = Math.floor(Math.random() * 3) + 1; console.log("rndX: " + rndX); console.log("rndY: " + rndY); speedXBall = - speedXBall; speedYBall = - speedYBall; xBall += speedXBall - 1; yBall += speedYBall - 1; divBall.style.left = xBall + "px"; divBall.style.top = yBall + "px"; } if (xBall > 800 || xBall < 0){ speedXBall = - speedXBall; } if (yBall > 600 || yBall < 0){ speedYBall = - speedYBall; } } } document.onkeydown = function(e) { let divPaddle= document.getElementById("divPaddle"); switch (e.keyCode) { case 37: xPaddle -= speedXPaddle; break; case 39: xPaddle += speedXPaddle;; break; } divPaddle.style.setProperty("left", xPaddle + "px"); }; function checkCollision(divBall, divPaddle){ let isCollision = false; let rect1 = divBall.getBoundingClientRect(); let rect2 = divPaddle.getBoundingClientRect(); rect1.width = Math.round(rect1.width); rect1.height = Math.round(rect1.height); rect1.left = Math.round(rect1.left); rect1.top = Math.round(rect1.top); rect2.width = Math.round(rect2.width); rect2.height = Math.round(rect2.height); rect2.left = Math.round(rect2.left); rect2.top = Math.round(rect2.top); if ((rect1.left + rect1.width > rect2.left && // right rect2.left + rect2.width > rect1.left && // left rect1.top + rect1.height + 1 > rect2.top && // down rect1.top < rect2.top) // rect 1 is above rect 2 || (rect1.left + rect1.width + 1 > rect2.left && // right rect1.top + rect1.height > rect2.top && // down rect2.top + rect2.height > rect1.top && // up rect1.left < rect2.left) // rect1 is on the left of rect2 || (rect2.left + rect2.width + 1 > rect1.left && // left rect1.top + rect1.height > rect2.top && // down rect2.top + rect2.height > rect1.top && // up rect1.left > rect2.left)){ // rect1 is on the right of rect2 isCollision = true; }else{ isCollision = false; } return isCollision; }