【发布时间】:2016-07-25 19:01:24
【问题描述】:
在我之前的问题here. 中,我成功地了解了如何从图像中读取和绘制每一帧的关卡。
现在我已经输入了一个 Player 类,尽管代码没有这样做,但玩家的移动确实很不稳定。我知道这一点,因为如果我将关卡阅读代码注释掉,玩家就可以正常移动。
我认为这是 foreach 循环这样做的。我不知道,我们将不胜感激!
只是为了节省您点击的时间,这是我成功的级别阅读代码。
public void readLevel(string path, GraphicsDevice graphics)
{
//GET AN ARRAY OF COLORS
Texture2D level = Content.Load<Texture2D>(path);
Color[] colors = new Color[level.Width * level.Height];
level.GetData(colors);
//READ EACH PIXEL AND DRAW LEVEL
Color brickRGB = new Color(128, 128, 128);
Color blankRGB = new Color(87, 0, 127);
int placeX = 0;
int placeY = 0;
foreach (Color pixel in colors)
{
SpriteBatch spriteBatch = new SpriteBatch(graphics);
spriteBatch.Begin();
if (pixel == brickRGB)
{
Texture2D brick = Content.Load<Texture2D>("blocks/brick");
spriteBatch.Draw(brick, new Rectangle(placeX, placeY, 40, 40), Color.White);
Rectangle rect = new Rectangle(placeX, placeY, 40, 40);
blocks.Add(rect);
}
else if (pixel == blankRGB)
{
Texture2D back = Content.Load<Texture2D>("titlescreen/back");
spriteBatch.Draw(back, new Rectangle(placeX, placeY, 40, 40), Color.White);
}
if (placeX == 840)
{
placeX = 0;
placeY += 40;
}
else placeX += 40;
spriteBatch.End();
}
}
Game.cs:
class Game
{
Player player;
LevelReader reader;
int level = 1;
public Game(ContentManager content)
{
reader = new LevelReader(content);
player = new Player(content);
}
public void Update()
{
player.Update();
}
public void Draw(GraphicsDevice graphics)
{
reader.readLevel("levels/l" + level, graphics);
player.Draw(graphics);
}
}
【问题讨论】:
-
每帧加载关卡纹理 (
Content.Load...) 可能不是最好的主意,性能方面。除此之外,level.Width和level.Height的实际值是多少? -
我正在读取的图像是 22*15,因此我们在 foreach 循环中每帧循环 330 次,这也可能不是一个好主意。但我不知道有什么替代方法,不过我会修复每帧加载关卡的问题。
-
除非你有一个精心设计的内容流系统(我没有看到任何证据),否则你不应该在游戏过程中调用
Content.Load,当然也不是每一帧。如果它是静态的,您应该在LoadContent期间执行所有此类操作