c# - Foreach loop causing lag? -
in previous question here. found out how read , draw level each frame image.
now have inputted player class, player moves choppy despite code not doing so. know because if comment level reading code out, player moves fine.
i think it's foreach loop doing this. have no idea , appreciated!
just save time clicking, here's successful level-reading code.
public void readlevel(string path, graphicsdevice graphics) { //get array of colors texture2d level = content.load<texture2d>(path); color[] colors = new color[level.width * level.height]; level.getdata(colors); //read each pixel , 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 = 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); } }
you might want move calls spritebatch.begin()
, spritebatch.end()
outside of 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 = 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();
Comments
Post a Comment