Javascript游戏; 放慢速度和冻结!怎么解决?

DFe*_*oso 7 javascript garbage-collection

我开始编写一个javascript塔防; 到目前为止,我的仆从在轨道上运动.但是我遇到了很大的麻烦,游戏突然冻结了几秒钟.我猜这是垃圾收集器正在做的工作,任何关于如何解决这个问题的想法都会非常好,因为我打算在游戏中添加更多的元素,我不想继续编码直到我得到这完美流淌!

到目前为止,代码非常简单; 你可以在这里看看

这是代码:

<html>
<head>
    <style>
        #game{
            background:red;
            width:500px;            
            height:500px;           
            position:relative;          
        } 
        .mostro {
            background:black;
            width:15px;         
            height:15px;            
            position:absolute;          
        }
    </style>
</head>
<body>
<div id="game">
<script type="text/javascript">
waypoint_x = [40, 140, 140, 220, 220, 80, 80, 340, 340, 420, 420];
waypoint_y = [140, 140, 60, 60, 240, 240, 320, 320, 100, 100, -20];
delay = 25;
new_monster = 0;
monsters_placed = 0;
monsters = [];
var d = new Date();
dist_x = 0;
dist_y = 0;
angle = 0;
mostro="";
total_monsters = 5;
function runGame() {
    if (monsters_placed<total_monsters) {
        new_monster++;
    }
    if (new_monster == delay) {
        new_monster = 0;
        document.getElementById("game").innerHTML = document.getElementById("game").innerHTML + '<div class="mostro" id="mostro-'+monsters_placed+'"></div>';
        monsters_placed++;
    }
    for (i=0;i<monsters_placed;i=i+1)   {
            mostro = monsters[i];
            dist_x = waypoint_x[mostro.point_to_reach] - mostro._x;
            dist_y = waypoint_y[mostro.point_to_reach] - mostro._y;
            if ((Math.abs(dist_x) + Math.abs(dist_y)) < 1) {
                monsters[i].point_to_reach++;
            }
            angle = Math.atan2(dist_y, dist_x);
            mostro._x = mostro._x + mostro.speed * Math.cos(angle);
            mostro._y = mostro._y + mostro.speed * Math.sin(angle);
            monsters[i]._rotation = angle/Math.PI*180-90    
        document.getElementById("mostro-"+i).style.left = Math.ceil(mostro._x) + "px";
        document.getElementById("mostro-"+i).style.top = Math.ceil(mostro._y) + "px";
    }
}

function setUpGame(){
    for(i=0;i<=total_monsters;i++){
        monsters[i] = new Object();
        monsters[i].point_to_reach = 0;
        monsters[i].speed = 1;
        monsters[i]._x = 0;
        monsters[i]._y = 0;
    }
}
setUpGame();
setInterval(runGame,10);
</script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

rah*_*hul 2

它不是垃圾收集器在做这项工作,而是在您的代码中,当您尝试设置顶部和左侧位置时,在特定时间您尝试设置的值不是数字。所以代码就崩溃了......

我认为当移动的 div 穿过红色背景的容器顶部时就会发生这种情况。