js 游戏摇杆 智能小车 方向盘

廉价感情. 提交于 2020-01-18 09:13:17

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>
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!