【发布时间】:2017-08-19 12:39:21
【问题描述】:
我正在创建一个作为学校项目的游戏,并认为使用颜色映射来创建关卡是个好主意,但是由于某种原因,我使用的方法非常很慢。
public List<Entity> LoadLevel(Level level)
{
List<Entity> ents = new List<Entity>();
Color[] clrs = new Color[level.getColorMap.Height*level.getColorMap.Width];
level.getColorMap.GetData(clrs);
for (int x = 0; x < level.getColorMap.Width; x++)
{
for (int y = 0; y < level.getColorMap.Height; y++)
{
if (clrs[x + y * level.getColorMap.Width] == new Color(0, 0, 0))
{
ents.Add(new Terrain(new Vector2(x, y)));
ents.Last().Animation.setImageIndex(0);
ents.Last().Animation.Play();
}
if (clrs[x + y * level.getColorMap.Width] == new Color(6, 6, 6))
{
ents.Add(new Terrain(new Vector2(x, y)));
ents.Last().Animation.setImageIndex(6);
ents.Last().Animation.setSpeed(69);
ents.Last().Animation.Play();
}
if (clrs[x + y * level.getColorMap.Width] == new Color(9, 9, 9))
{
ents.Add(new Terrain(new Vector2(x, y)));
ents.Last().Animation.setImageIndex(9);
ents.Last().Animation.setSpeed(69);
ents.Last().Animation.Play();
}
}
}
return ents;
}
我在LoadContent()中调用了这个函数,执行大约需要半分钟,为什么这么慢?
【问题讨论】:
-
这个更适合code review
-
level.getColorMap.Height和level.getColorMap.Width有多大? -
它们都是 2048 大。
-
我们不知道所有这些动画方法的作用。注释所有以“ents.”开头的行。它有帮助,问题不在此代码中。
-
@AntonínLejsek 它可能在这段代码中。例如,
getColorMap可能正在从磁盘加载颜色图。你是对的,“成本”在这段代码之外,但它仍然可以在这里改进。在任何情况下,不断访问level.getColorMap和level.getColorMap.Width而不是将其存储在局部变量中,这有点异味。还有就是缺少else if而不是多余的计算。
标签: c# performance xna nested-loops monogame