我正在制作一款游戏,您可以在这里测试:http://jaminweb.com/projs/snakegame.php
尝试将速度设置为快,并注意蛇在碰到食物后如何变得非常慢。撞击食物 10 次后,它变得 super 慢。一定存在某种类型的性能泄漏,但我很难找到。
以下是当蛇碰到食物时执行的代码块:
if (this.boxCollision(BBhead, BBfood))
{
this.moveFood(this.canvHeight, this.canvWidth);
this.score += 10;
document.getElementById("snake-score-div").innerHTML = this.score.toString();
addLink = true;
}
if (addLink)
this.body.push(this.body[this.body.length - 1].clone());
其中函数moveFood
由
snakegame.prototype.moveFood = function()
{
var bbf = this.food.getBBox(); // bounding box for food
do
{
// tx, ty: random translation units
tx = randInt(0, this.canvWidth / this.linkSize - 1) * this.linkSize - bbf.x;
ty = randInt(0, this.canvHeight / this.linkSize - 1) * this.linkSize - bbf.y;
// translate copy of food
this.food.translate(tx, ty);
// update bbf
bbf = this.food.getBBox();
} while (this.hitSnake(bbf));
}
以及函数clone
和translate
来自这个库:http://raphaeljs.com/reference.html
该过程的某些原因导致一切变慢。知道为什么吗?
最佳答案
如果您使用的是 Chrome 或 Firefox,您可以将某些操作包装在 console.time 中,以查看哪个操作造成了问题。我建议:
if (this.boxCollision(BBhead, BBfood))
{
console.time('Moving food');
this.moveFood(this.canvHeight, this.canvWidth);
console.timeEnd('Moving food');
console.time('Increasing score');
this.score += 10;
console.timeEnd('Increasing score');
console.time('Updating score display');
document.getElementById("snake-score-div").innerHTML = this.score.toString();
console.timeEnd('Updating score display');
addLink = true;
}
if (addLink) {
console.time('Body clone');
this.body.push(this.body[this.body.length - 1].clone());
console.timeEnd('Body clone');
}
然后检查您的控制台并观察数字。
关于javascript - 这会导致性能泄漏还是其他原因?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27465133/