我正在开发一个HTML5 2D等距游戏引擎(想想sim city 2000)。我希望提高帧率,我感觉我的代码效率非常低。下面的代码循环遍历从地图背面(北部)到前部(南部)的所有瓷砖精灵:
var xTile = 0;
var yTile = 0;
for (var i = 0; i < mapWidth; i++) {
for (var j = mapHeight; j >= 1; j--) {
// What tile are you drawing?
var currentTile = new Image();
if (mapArray[i][j - 1] === "g") {
currentTile = grass;
}
else if (mapArray[i][j - 1] === "s") {
currentTile = sand;
}
else if (mapArray[i][j - 1] === "w") {
currentTile = water;
}
// Calculate where to draw the tile
xPosition = ((j * tileWidth / 2) + (i * tileWidth / 2));
yPosition = ((i * tileHeight / 2) - (j * tileHeight / 2));
if (currentTile.height !== 32) {
yPosition = yPosition - (currentTile.height - 32);
}
// draw tile
ctx.drawImage(currentTile, locationModifierX + xPosition - (tileWidth / 2), locationModifierY + yPosition + 250 - (heightArray[i][j - 1] * 16));
yTile++;
// Return to the beginning of the y row if the end has been reached
if (yTile >= 16) {
yTile = 0;
}
}
xTile++;
}
基本上我试图理解如何提高绘制周期的速度和效率,因为我认为它比基于浏览器的游戏更重要。我想我会将最佳答案判断为第一个提供合理帧速率改善的答案。
我希望这个问题不是太模糊,但我想有很多可能的答案......
可能的改进 -----
var xTile = 0;
var yTile = 0;
var currentTile = new Image();
// Tile Loop
for (var i = 0; i < mapWidth; i++) {
for (var j = mapHeight; j >= 1; j--) {
// What tile are you drawing?
if (mapArray[i][j - 1] === "g") {
currentTile = grass;
}
else if (mapArray[i][j - 1] === "s") {
currentTile = sand;
}
else if (mapArray[i][j - 1] === "w") {
currentTile = water;
}