js 游戏摇杆 智能小车 方向盘
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>js 游戏摇杆 智能小车方向盘</title>
<meta name="viewport"
content="width=device-width,initial-scale=1,
minimum-scale=1,maximum-scale=1,user-scalable=no" />
<style>
* {
margin: 0;
padding: 0;
}
body{
background: rgba(175, 175, 175, 0.2);
}
.div1 {
width: 200px;
height: 200px;
background: rgba(0, 0, 0, 0.15);
border-radius: 100%;
position: absolute;
top: 50%;
left: 50%;
margin-left: -100px;
margin-top: -100PX;
}
.div2 {
width: 50px;
height: 50px;
background: rgb(255, 255, 255);
border-radius: 100%;
position: absolute;
top: 50%;
left: 50%;
margin-left: -25px;
margin-top: -25px;
}
.div3 {
width: 200px;
height: 200px;
border-radius: 100%;
position: absolute;
top: 50%;
left: 50%;
margin-left: -100px;
margin-top: -100PX;
}
</style>
</head>
<body>
<div class="div1"></div>
<div class="div2"></div>
<div class="div3"></div>
<script>
let div3 = document.querySelector('.div3')
let div2 = document.querySelector('.div2')
let r = 25 //摇杆的半径
let r2 = 100 //底盘的半径
let x = div2.offsetLeft + r //加上r半径的偏移到中心
let y = div2.offsetTop + r
div3.ontouchmove = (e) => {
let t = e.changedTouches[0]
//开根 触摸点到摇杆中心点的距离
let d = Math.sqrt(Math.pow(t.pageX - x, 2) + Math.pow(t.pageY - y, 2))
d=d>(r2-r)?r2-r:d
//三角函数求反正切 减去xy偏移到中心点
let radin = Math.atan2(t.pageY - y, t.pageX - x)
let vx = x + Math.cos(radin) * d
let vy = y + Math.sin(radin) * d
div2.style.left = vx + 'px'
div2.style.top = vy + 'px'
}
div3.ontouchend = () => {
div2.style.left = x + 'px'
div2.style.top = y + 'px'
}
</script>
</body>
</html>
来源:CSDN
作者:MCU 求学者
链接:https://blog.csdn.net/weixin_45426238/article/details/103831217