Question

Recently I've been trying to develop a 2D Terraria style game using SFML and c++. Everything has been working perfectly expect for the random terrain generation. Currently, I have a for loop that assigns the position and texture to an array of sprites (ex:int grass[150]) which are then drawn to the screen using a for loop. The terrain generates and looks okay but, the multiple arrays of sprites are being drawn to the screen every time my program loops. This is causing some serious performance issues, because currently around 1400 sprites (only a fraction of number of the amount I want when the game is finished) are being drawn every time my program loops.

So, my question to you is how do I make my terrain generate efficiently? Is there a way to only clear a portion of the sprites on the screen at a time or only clear sprite when it is modified? Is there a better way to create terrain other than using multiple arrays of sprites?

Was it helpful?

Solution 2

I think there's a few confusions in your question, but here are some points you should look into :

  • As others pointed out, only draw the terrain tiles that are actually on screen. You do not need to draw the whole world at each frame.

  • If you world dosen't change (or doesn't change much except by player's action), you could try to render it once and for all and cache this rendering into a texture that you would display (with the good offset corresponding to the in-game position of the player). No more looping through tiles and arrays. Take a look at RenderTexture. Of course if your player can dig or do whatever changes the world, you can't use this texture forever, but it may be a good idea to do it after every change, as changes don't happen so often compared to rendering, so I guess you could still benefit from this.

  • You mentionned an array of sprites. I hope you don't have an instance of a sf::Sprite for every single grass tile, every single rock tile etc. ? In case you do, only have one sprite of each tile, and use it to draw every tiles of its type just by changing its coordinates and drawing it to your render target. But I may have misunderstood your question.

OTHER TIPS

Try drawing less tiles, there's no need to draw every tile in the world as the majority of them aren't visible.

Draw only the amount of tiles that can be visible on the screen at one time plus a bit more, for example if the screen can only fit 7x4 tiles draw around 9x6.

That will help reduce the time spent trying to draw non-visible tiles.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top