var $box = document.getElementById('box'); var $table = document.getElementById('table'); var speed = 1; var direction = 190; var move = true; var left = {x: 0, y: 0, width: 80, height: 600} var right = {x: 720, y: 0, width: 80, height: 600} var up = {x: 0, y: 0, width: 640, height: 80} var bottom = {x: 6, y: 520, width: 640, height: 80} var box = {x: 100, y: 100, width: 100, height: 100} function collision(){ if (box.x < left.x + left.width && box.x + box.width > left.x && box.y < left.y + left.height && box.height + box.y > left.y) { speed = 0; box.x += 1; $box.style.left = box.x; } else if (box.x < right.x + right.width && box.x + box.width > right.x && box.y < right.y + right.height && box.height + box.y > right.y) { speed = 0; box.x -= 1; $box.style.left = box.x; } else if (box.x < up.x + up.width && box.x + box.width > up.x && box.y < up.y + up.height && box.height + box.y > up.y) { speed = 0; box.y += 1; $box.style.top = box.y; } else if (box.x < bottom.x + bottom.width && box.x + box.width > bottom.x && box.y < bottom.y + bottom.height && box.height + box.y > bottom.y) { speed = 0; box.y -= 1; $box.style.top = box.y; } } function moveBox() { setTimeout(function () { if(direction > 0 && direction < 90){ $table.setAttribute("class", "up-left"); } if(direction > 90 && direction < 180){ $table.setAttribute("class", "up-right"); } if(direction > 180 && direction < 270){ $table.setAttribute("class", "down-right"); } if(direction > 270 && direction < 360){ $table.setAttribute("class", "down-left"); } box.y -= speed * Math.sin(direction * (Math.PI/180)); box.x -= speed * Math.cos(direction * (Math.PI/180)); //console.log(box.x); $box.style.top = Math.round(box.y) + "px"; $box.style.left = Math.round(box.x) + "px"; speed += 0.3; collision(); if (move) { moveBox(); } }, 20) } function findAngle(a,b,c) { var ab = Math.sqrt(Math.pow(b.x-a.x,2)+ Math.pow(b.y-a.y,2)); var bc = Math.sqrt(Math.pow(b.x-c.x,2)+ Math.pow(b.y-c.y,2)); var ac = Math.sqrt(Math.pow(c.x-a.x,2)+ Math.pow(c.y-a.y,2)); var degrees = (Math.acos((bc*bc+ab*ab-ac*ac)/(2*bc*ab))) * (180/Math.PI); return degrees; } document.onmousemove = function(e){ var a = {x: e.pageX, y: e.pageY} var b = {x: window.innerWidth/2, y: window.innerHeight/2} var c = {x: 0, y: window.innerHeight/2} speed = 1; angle = findAngle(a,b,c); if(e.pageY < window.innerHeight/2){ direction = Math.round(angle); }else{ direction = Math.round(360-angle); } }; moveBox();