Foreach 循环导致滞后? [英] Foreach loop causing lag?
问题描述
在我之前的问题这里. 我成功地找到了如何从图像中读取和绘制每一帧的关卡.
In my previous question here. I successfully found out how to read and draw a level each frame from an image.
现在我已经输入了一个 Player 类,尽管代码没有这样做,但播放器的移动真的很不稳定.我知道这一点,因为如果我注释掉关卡读取代码,玩家就会移动得很好.
Now that I have inputted a Player class, the player moves really choppy despite the code not doing so. I know this because if I comment the level reading code out, the player moves fine.
我认为这是 foreach 循环执行此操作.我不知道,我们将不胜感激!
I think it's the foreach loop doing this. I have no idea and help would be appreciated!
为了节省您点击的时间,这是我成功的关卡阅读代码.
Just to save you time from clicking, here's my successful level-reading code.
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);
}
}
推荐答案
您可能希望将调用移至 spritebatch.Begin()
和 spritebatch.End()
在你的循环之外.
You might want to move the calls to spritebatch.Begin()
and spritebatch.End()
outside of your loop.
SpriteBatch spriteBatch = new SpriteBatch(graphics);
spriteBatch.Begin();
foreach (Color pixel in colors)
{
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();
这篇关于Foreach 循环导致滞后?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!