I am running into lag when loading many sprites onto the screen. If I have less than 12 on the screen it runs smoothly until I add a couple more and then it bogs down.
I currently have this as my detection code;
public void Collision(Sprite sprite, Rectangle newRectangle, bool passable, bool speedRestricted, int xOffset, int yOffset)
{// Tile boundaries
if (sprite.Bounds.Top(newRectangle) && passable == false)
{
animation.Position = new Vector2(sprite.Position.X, (newRectangle.Y - sprite.Bounds.Height));
}
if (sprite.Bounds.Left(newRectangle) && passable == false)
{
animation.Position = new Vector2((newRectangle.X - sprite.Bounds.Width), sprite.Position.Y);
}
if (sprite.Bounds.Right(newRectangle) && passable == false)
{
animation.Position = new Vector2((newRectangle.X + sprite.Bounds.Width), sprite.Position.Y);
}
if (sprite.Bounds.Bottom(newRectangle) && passable == false)
{
animation.Position = new Vector2(sprite.Position.X, (newRectangle.Y + sprite.Bounds.Height));
}
}
It is called in like this;
foreach (var tile in map.CollisionTiles)
{
player.Collision(player, tile.Rectangle, tile.Passable, tile.SpeedRestricted, map.Width, map.Height);
foreach (var sprite in sprites)
{
sprite.Collision(sprite, tile.Rectangle, tile.Passable, tile.SpeedRestricted, map.Width, map.Height);
}
}
Now collision detection works perfectly so I don't have an issue there it's just when there are lots of sprites in my List<Sprite> sprites
does it lag. If I remove the collision detection from the code I can load thousands of sprites onto the map.
Question: How do I limit the detection area for the sprites so it only compares the tiles around the sprite instead of all the tiles on the map for each sprite.
I have looked through the other questions and found none when it comes to multiple sprite detections for tile maps, just the main player's collision detection.