首页 > 解决方案 > JavaScript 盒子游戏 - 内部 div 超出外部 div 边界

问题描述

我的 github 上的 Box Game

我无法让内部 div 在移动视图中正确地停留在外部 div 的边界内。请通过检查此代码有什么问题来帮助我。我是 JavaScript 新手。

HTML

                <div class="GameArea">
                    <div class="message">
                        <h4>How to Play</h4>
                        <div>
                            Just click on the blue box to score points!
                        </div>
                        X:<span class="x">0</span>
                        Y:<span class="y">0</span>
                        <br>
                        Score <span class="score">0</span>
                    </div>
                    <div class="output">
                        <div><h4 class="text-center banner">Let's start!</h4></div>
                    </div>
                </div>

JS

function move() {
    let speed = Math.random() * 10;
    const box = document.querySelector(".box");
    let bounds = output.getBoundingClientRect();
    box.steps--;
    if (box.steps < 0) {
        box.direction = Math.floor(Math.random() * 4);
        box.steps = Math.random() * 20;
    }
    if (box.direction == 0 && box.x < bounds.right - 440) {
        box.x += speed;
    }
    if (box.direction == 1 && box.x > bounds.left) {
        box.x -= speed;
    }
    if (box.direction == 2 && box.y < bounds.bottom - 165) {
        box.y += speed;
    }
    if (box.direction == 3 && box.y > bounds.top) {
        box.y -= speed;
    }
    box.style.top = box.y + "px";
    box.style.left = box.x + "px";
    window.requestAnimationFrame(move);
}

标签: javascripthtmljqueryperformancejavascript-objects

解决方案


推荐阅读