Potrzebuje pomocy w ulepszeniu gry. Do dyspozycji mam dwa divy jeden powinien "popychać" ten drugi w trakcie ruchu. Zaprezentowany skrypt działa ale ma swoje mankamenty, cały czas mam problem z uściśleniem warunków. Pozwalam sobie na pominięcie pliku html i css, niemniej są tam błędów nie ma.
let rect = document.getElementById('rect');
let rect2 = document.getElementById('rect2');
let position = findPos(rect);
function findPos(obj) {
var nleft = 0;
var ntop = 0;
if (obj.offsetParent) {
nleft = obj.offsetLeft
ntop = obj.offsetTop
while (obj = obj.offsetParent) {
nleft += obj.offsetLeft
ntop += obj.offsetTop
}
}
return [nleft,ntop];
}
function changePos() {
console.log("zółty kwadrat x = " + ((findPos(rect2)[0])) + " y = " + ((findPos(rect2)[1])));
console.log("czarny kwadrat x = " + ((findPos(rect)[0])) + " y = " + ((findPos(rect)[1])));
if(findPos(rect)[0] === findPos(rect2)[0]) {;
if(findPos(rect)[1]+100 === findPos(rect2)[1]) {
rect2.style.top = (findPos(rect)[0])+100 + "px";
}
if(findPos(rect)[1]-100 === findPos(rect2)[1]) {
rect2.style.top = (findPos(rect)[0])-100 + "px";
}
}
if(findPos(rect)[1] === findPos(rect2)[1]) {
if(findPos(rect)[0]-100 === findPos(rect2)[0]) {
rect2.style.left = (findPos(rect)[1])+100 + "px";
}
if(findPos(rect)[0]+100 === findPos(rect2)[0]) {
rect2.style.left = (findPos(rect)[1])-100 + "px";
}
}
}
window.addEventListener('keydown', function(event) {
switch (event.keyCode) {
case 37:
console.log("Left");
rect.style.left = (findPos(rect)[0])-20 + "px";
break;
case 39:
console.log("Right");
rect.style.left = findPos(rect)[0] + "px";
break;
case 38:
console.log("Up");
rect.style.top = (findPos(rect)[1])-20 + "px";
break;
case 40:
console.log("Down");
rect.style.top = findPos(rect)[1] + "px";
break;
}
changePos();
}, false);