我正在开发一款针对Android的塔防游戏,并且在画布上绘制了大约500位图时,注意到帧速率严重下降(低至5~10)。我使用View#onDraw
方法更新并渲染塔防游戏,如下所示:
public void onDraw(Canvas canvas){
game.update();
game.render(canvas);
this.invalidate(); //Capped to 60fps using Thread#sleep
}
不需要很长时间就可以在画布上绘制这么多位图,因为这些塔会发射大约10枚抛射物/秒。因此,仅用4个塔就可以用12.5秒来达到这个数量的射弹。我见过其他塔式防御游戏,如Bloons Tower Defense,每帧画出数千个精灵,仍能以每秒60帧的速度运行。
位图存储在HashMap中,因此不必每帧都将它们加载到内存中。除了常识之外,我似乎无法进一步优化以提高绘图速度和随后的游戏帧速率。
这是我的射弹渲染代码。我已经读过在画布'矩阵上执行大量转换可能会导致性能不佳,但我没有看到任何其他方法来旋转弹丸而不执行这些转换:
public void render(Canvas canvas, Game game){
canvas.save();
canvas.rotate(Util.canvasRotate(getRotation()), x + attack.getWidth() / 2, y + attack.getHeight() / 2);
Object resource = game.getResources().get(attack.getResource());
if(resource instanceof Bitmap)
canvas.drawBitmap((Bitmap)resource, null, getBounds(), null);
else if(resource instanceof Animation)
canvas.drawBitmap(((Animation)resource).getFrame(game.getTime()), null, getBounds(), null);
canvas.restore();
}
getRotation
方法会计算一些数学角度:
float ty = centerY() - y;
float tx = centerX() - x;
float angle = (float)Math.toDegrees(Math.atan2(ty, tx));
return angle;
当有数十万个位图时,有没有更快的方法将Bitmaps绘制到画布上?如果没有,我可以在我的渲染方法中使用任何优化吗?
注意: 在绘制位图时,没有任何位图被调整大小 - 它们以相同的分辨率存储和绘制(射弹= 32x32塔= 72x72)。