我开始编写一个
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,220,80,340,420,420]; waypoint_y = [140,60,240,320,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>