/* // code of keys https://gcctech.org/csc/javascript/javascript_keycodes.htm arrow left 37 arrow up 38 arrow right 39 arrow down 40 w 87 s 83 a 65 d 68 */ x1 = 20; y1 = 30; x2 = 80; y2 = 50; document.onkeydown = function(e) { let info = document.getElementById("info"); let napis1 = document.getElementById("napis1"); let napis2 = document.getElementById("napis2"); switch (e.keyCode) { case 37: //alert('left'); x1 -= 1; break; case 38: //alert('up'); y1 -= 1; break; case 39: //alert('right'); x1 +=1; break; case 40: //alert('down'); y1 +=1; break; case 65: //alert('a'); x2 -=1; break; case 87: //alert('w'); y2 -=1; break; case 68: //alert('d'); x2 +=1;; break; case 83: //alert('s'); y2 +=1; break; } napis1.style.setProperty("left", x1 + "px"); napis1.style.setProperty("top", y1 + "px"); napis2.style.setProperty("left", x2 + "px"); napis2.style.setProperty("top", y2 + "px"); // collision // https://developer.mozilla.org/en-US/docs/Games/Techniques/2D_collision_detection // wymiary elementu // https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect let rect1 = napis1.getBoundingClientRect(); let rect2 = napis2.getBoundingClientRect(); info.innerHTML = Math.round(rect1.width) + " " + rect1.left + " " + rect1.top + "
" + Math.round(rect2.width) + " " + rect2.left + " " + rect2.top; /* var leftToRight = rect1.left + rect1.width > rect2.left; var rightToLeft = rect2.left + rect2.width > rect1.left; var upToDown = rect1.top + rect1.height > rect2.top; var DownToUp = rect2.top + rect2.height > rect1.top; */ var leftToRight = x1 + rect1.width > x2; var rightToLeft = x2 + rect2.width > x1; var upToDown = y1 + rect1.height > y2; var DownToUp = y2 + rect2.height > y1; if (leftToRight && rightToLeft && upToDown && DownToUp){ info.innerHTML += " collision!"; //alert("collision"); //napis2.style.display = "none"; //napis1.style.display = "none"; } }