游戏循环中的内存泄漏

时间:2012-01-04 23:36:23

标签: javascript memory-leaks raphael game-loop

我正在用javascript创建一个游戏,我的游戏循环每30ms调用一次,因为任务管理器显示firefox内存使用量在大约20秒内增加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。   任何想法导致问题的原因,如何在没有这些代码的情况下仍然可以旋转我的对象?

2 个答案:

答案 0 :(得分:3)

RaphaelJS中rotate的文档说明如下:

  

将给定点周围的给定角度的旋转添加到元素的变换列表中。

这当然听起来像是一个潜在的罪魁祸首。关键词有添加列表

当您将元素旋转两次时,transform函数会显示什么?我怀疑旋转调用会积累越来越大的变换字符串。如果这是正在发生的事情,你可以重置转换,

el.transform("");

这应该可以解决你所看到的问题。

答案 1 :(得分:2)

我的代码片段中没有任何内容会泄漏内存。

正如Eugen Rieck所指出的,Firefox(和其他人)有时候不会分配他们分配的GC和/或可用内存,直到他们真正有理由这样做。

您是否尝试过使用实际的内存分析工具来查看代码是否实际泄漏?我不确定Firefox是否有一个,但至少在Chrome中有一个。