我在javascript中創建遊戲,每30ms調用我的gameloop,它會泄漏大量內存,因爲任務管理器在大約20秒內顯示firefox內存使用量增加400mb。 我不熟悉如何確保內存在JavaScript中收集。遊戲循環中的內存泄漏
function GameLoop(tick) {
move(player1.ship);
}
function Player(name) {
this.id = 0;
this.name = name;
this.ship = Ship(this);
}
function Ship(player) {
this.pos = [1024/2, 768/2];
this.vel = [0, 0];
this.angle = 0;
this.acc = 0;
this.thrust = 0;
this.west = 0;
this.east = 0;
this.turnRate = 5;
this.player = player;
this.size = [40, 40];
this.ship = canvas.rect(this.pos[0], this.pos[1], this.size[0], this.size[1]);
this.ship.attr("fill", "red");
return this;
}
function move(ship) {
var angle = ship.angle;
var max_speed = 20;
var acc_speed = 300;
var acc = 0;
if (ship.thrust) {
acc = 0.25 * acc_speed;
}
else { //slow down
if ((acc - (0.25 * acc_speed)) > 0) {
acc -= 0.25 * acc_speed;
}
else {
acc = 0;
}
}
var speedx = ship.vel[0] + acc * Math.sin(angle);
var speedy = ship.vel[1] - acc * Math.cos(angle);
var speed = Math.sqrt(Math.pow(speedx,2) + Math.pow(speedy,2));
var speedx = ship.vel[0] + acc;
var speedy = ship.vel[1] - acc;
var speed = speedx + speedy;
if (speed > max_speed) {
speedx = speedx/speed * max_speed;
speedy = speedy/speed * max_speed;
}
ship.vel = [speedx, speedy];
ship.pos = [ship.pos[0] + speedx * 0.25, ship.pos[1] + speedy * 0.25];
ship.ship.attr({x: ship.pos[0], y: ship.pos[1]});
ship.ship.rotate(angle);
ship.angle = 0;
delete this.thrust;
delete this.west;
delete this.east;
delete old_angle;
delete angle;
delete max_speed;
delete acc_speed;
delete acc;
delete speedx;
delete speedy;
delete speed;
return this;
}
var player1 = new Player("Player 1");
setInterval(GameLoop, 30);
確定我註釋掉一些代碼,並已發現有問題的行,其
ship.ship.rotate(角度); 在發表評論後,JavaScript使用4500K。 任何想法,爲什麼這是造成這個問題,以及如何仍然旋轉我的對象沒有這一點的代碼?
'Player'的定義是什麼? – 2012-01-04 23:46:58
沒有什麼會泄漏,當然沒有什麼會泄漏幾乎1MB /循環。你如何顯示實際_does_的代碼?例如移動動畫?就像現在一樣,你只是改變'ship.angle','thrust'和'vel',而不是對它們做任何事情。 – 2012-01-04 23:47:49
哪個版本的Firefox? 7.0 FF只有在達到RAM的固定上限時纔會執行GC ... – 2012-01-04 23:49:13