美文网首页
js-圆形碰撞

js-圆形碰撞

作者: 一枚奋斗青年 | 来源:发表于2016-08-03 14:29 被阅读421次

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
*{margin:0;padding:0;}

div{
    position: absolute;
    width: 100px;
    height: 100px;
    font-size: 25px;
    line-height: 100px;
    text-align: center;
    border-radius:50%;
}
#move_box{
    background: red;
    cursor: pointer;

}
#hit_box{
    left: 200px;
    top: 200px;
    background: blue;

}
#hit_box2{
    left: 350px;
    top: 200px;
    background: blue;
    /*height: 150px;*/
    border-radius:50%;
}
</style>

</head>
<body>
<div id="move_box">移动</div>
<div id="hit_box">被撞</div>
<div id="hit_box2">被撞</div>
</body>

<script>
    // 获取元素对象
    var moveBox = document.getElementById("move_box");
    // var hitBoxes = document.querySeletorAll("#hit_box #hit_box2");
    var hitBox = document.getElementById("hit_box");
    var hitBox2 = document.getElementById("hit_box2");
    var hitBoxes = [hitBox,hitBox2];

    // 碰撞函数
    function circleHit(circle1,circle2){
        // 移动对象园的偏移量
        var r1 = circle1.offsetWidth / 2;
        var l1 = circle1.offsetLeft;
        var t1 = circle1.offsetTop;
        // 被撞对象的圆偏移量
        var r2 = circle2.offsetWidth / 2; //园2的半径
        var l2 = circle2.offsetLeft;
        var t2 = circle2.offsetTop;

        //用圆1的偏离量+园1的半径 - 园2的偏移量 + 园2的半径
        var a = (l1 + r1) - (l2 + r2); // 左偏移量
        var b = (t1 + r1) - (t2 + r2); //上偏移量

        //勾股定理求两个圆的圆心距离
        var c = Math.sqrt(a * a + b * b);

        if (c>=(r1+r2)) {
            return true;
        }else{
            return false;
        }
    }

    // 为移动元素添加鼠标按下的事件
    moveBox.onmousedown = function(event){
        var event = event || window.event;

        // 获取鼠标在移动元素内的坐标点
        var disX = event.clientX - moveBox.offsetLeft;
        var disY = event.clientY - moveBox.offsetTop;

        // 为doc文档添加移动事件
        document.onmousemove = function(event){
            var event = event || window.event;

            // 获取移动距离的偏移量
            var x = event.clientX - disX;
            var y = event.clientY - disY;

            // 循环每一个被撞的对象
            for (var i = 0; i < hitBoxes.length; i++) {
                // 调用被撞函数
                var bool = circleHit(moveBox,hitBoxes[i]);

                // 判断
                if (bool) {
                    hitBoxes[i].style.backgroundColor = "blue";
                    hitBoxes[i].innerHTML = "被撞";
                }else{
                    hitBoxes[i].style.backgroundColor = "green";
                    hitBoxes[i].innerHTML = "撞上";
                }
            }

            moveBox.style.left = x + "px";
            moveBox.style.top = y + "px";
        }
    }
    // 鼠标抬起
    moveBox.onmouseup = function(){
        document.onmousemove = null;
    }
</script>

</html>

相关文章

网友评论

      本文标题:js-圆形碰撞

      本文链接:https://www.haomeiwen.com/subject/fdzfsttx.html