Здравствуйте! Подскажите пожалуйста. Как реализовать отбивание ракеткой шарика, и почему когда курсор мышки попадает на шарик, ракетка убегает влево?
Спасибо!
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
#pole{
width:600px;
height:400px;
border:1px #000 solid;
position: relative;
margin:auto;
}
#ball{
position: absolute;
top:0px;
left:0px;
width:30px;
height:30px;
background: #f00;
border-radius:50%;
}
#palka{
position: absolute;
bottom:0;
left:0;
width:80px;
height:10px;
background: #000;
}
#place{
width:600px;
height:400px;
margin:auto;
}
</style>
</head>
<body>
<div id="pole">
<div id="ball"></div>
<div id="palka"></div>
</div>
<script>
[JS]var palka_var = document.getElementById('palka')
var ball = document.getElementById('ball')
var ball_width = (ball.getBoundingClientRect().width)
var ball_height = (ball.getBoundingClientRect().height)
var width = (pole.getBoundingClientRect().width)
var height = (pole.getBoundingClientRect().height)
var w,h;
var x=0,y=0;
//привязываем мышку к палке
pole.addEventListener('mousemove',function(e){palka_var.style.left = e.offsetX - palka.getBoundingClientRect().width / 2 +"px"
//ограничиваем движение палки справа
if(e.offsetX >= width - palka.getBoundingClientRect().width / 2){palka_var.style.left = width - palka.getBoundingClientRect().width + "px"}
//ограничиваем движение палки слева
if(e.offsetX <= 0 + (palka.getBoundingClientRect().width / 2)){palka_var.style.left ="0" + "px"}
//отбиваем шарик
})
// console.log(y)
var sett = setInterval(moving,4);
function moving(){
ball.style.top = y+'px'
ball.style.left = x+'px'
// console.log(x)
if(x >= (width - ball_width)){w = false}
if(y >= (height - ball_height)){h = false}
if(x <= 0){w = true}
if( y<= 0){h = true}
if(w == true && h == true){x++; y++}
if(h == true && w == false){x--; y++;}
if(h == false && w == false){x--; y--;}
if(h == false && w == true){x++; y--}
}[/JS]
</script>
</body>
</html>