JavaScript - 重力 setInterval() - 平台碰撞

JavaScript - Gravity setInterval() - Platform Collision

我使用 parseInt(its.style.top) 将一个 img 元素编程到 "fall" 下 window,由正文中的 setInterval(fall,1000) 函数触发。

Moves()函数触发后出错,fall()函数停止调用。是否有 Moves() 函数的 if 语句在 img s.style.left >= r.style.width 之后再次调用 setInterval(fall,1000)?

谢谢! :-)

<html>
<body onload="setInterval(fall,1000)" onkeydown="Moves()">

<img id="square" style="position:absolute; left:10px; top:0px;    
width:50px; height:50px; background-color:red;" />

<img id="rectangle" style="position:absolute; left:10px; top:130px; 
width:150px; height:10px; background-color:blue;" />

<script>

function fall(){
var s = document.getElementById("square");
s.style.top = parseInt(s.style.top) + 25 + 'px';


var r = document.getElementById("rectangle");
r.style.top=130 + 'px';

if(s.style.top>=r.style.top){s.style.top=r.style.top;}
}

function Moves(){
var s = document.getElementById("square");
if (event.keyCode==39) { 
s.style.left = parseInt(s.style.left)+10+'px';}

var r = document.getElementById("rectangle");
r.style.width=150 + 'px';

if(s.style.left>=r.style.width){setInterval(fall,1000);}
}

</script>

</body> </html>

我相信这就是你想要做的:

<html>
<body onload="setTimeout(fall,1000)" onkeydown="Moves()">

    <img id="square" style="position:absolute; left:10px; top:0px;    
    width:50px; height:50px; background-color:red;" />

    <img id="rectangle" style="position:absolute; left:10px; top:130px; 
    width:150px; height:10px; background-color:blue;" />

    <script>
        var over_edge = false;
        var can_fall = true;

        function fall(){
            var s = document.getElementById("square");
            s.style.top = parseInt(s.style.top) + 25 + 'px';


            var r = document.getElementById("rectangle");
            //r.style.top=130 + 'px';

            if(!over_edge) {
                if(parseInt(s.style.top) >= parseInt(r.style.top) - parseInt(s.style.height)) {
                    s.style.top = parseInt(r.style.top) - parseInt(s.style.height);
                    can_fall = false;
                }
            }
            if(can_fall || over_edge)
                setTimeout(fall, 1000);
        }

        function Moves(){
            var s = document.getElementById("square");
            if (event.keyCode==39) { 
                s.style.left = parseInt(s.style.left)+10+'px';}

                var r = document.getElementById("rectangle");
                //r.style.width=150 + 'px';

                if(parseInt(s.style.left) >= parseInt(r.style.left) + parseInt(r.style.width)) {
                    if(!over_edge) {
                        over_edge = true;
                        fall();             // trigger falling over the edge but only once
                    }
                }
            }

    </script>
</body>
</html>