JavaScript制作游戏摇杆方向盘

JavaScript制作游戏摇杆方向盘

  • JavaScript制作游戏摇杆方向盘

JavaScript制作游戏摇杆方向盘

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;
        }

        .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>

结果
JavaScript制作游戏摇杆方向盘_第1张图片

你可能感兴趣的:(JavaScript小功能案例,javascript)