javascript技巧

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > javascript技巧 > 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制作游戏摇杆方向盘的文章就介绍到这了,更多相关JavaScript 游戏摇杆 内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家! 

您可能感兴趣的文章:
阅读全文