SFML community forums
Help => Graphics => Topic started by: lethoz on February 15, 2009, 04:58:47 pm
-
Hi,
i did very much research in this forum how to implement scrolling tilemaps with SFML.
I read the post from Petri Irri how to archive scrolling of tile maps(http://www.sfml-dev.org/forum/viewtopic.php?t=773&highlight=scroll+tilemap). But i cannot get mine to work .
Here's what i got:
1) I got code to load and manage tiles.
2) I can draw a tilemap that fills out the screen. (every tile is 48x48)
3) I can move the player sprite around the screen.
But that code doesn't work too well:
Game Loop:
// Clear screen
App.Clear();
if (Input.IsKeyDown(sf::Key::Up)) OffsetY = -48;
if (Input.IsKeyDown(sf::Key::Left)) OffsetX = -48;
if (Input.IsKeyDown(sf::Key::Down)) OffsetY += 48;
if (Input.IsKeyDown(sf::Key::Right)) OffsetX += 48;
View.Move(OffsetX, OffsetY); // Move the player
App.SetView(View); // Draw relative to the world
// maxHeight /maxWidht are the maximum tiles that are visible
for (int i=0;i<maxHeight;i++)
{
for (int j=0;j<maxWidth;j++)
{
CTile* tmpTile = new CTile(tileNames[map[i][j]]);
tmpTile->getTile().SetPosition ( j*48, i *48);
sf::Sprite sp = tmpTile->getTile();
App.Draw ( sp );
}
}
App.SetView(App.GetDefaultView()); // Draw relative to the GUI
App.Draw(Sprite); // Draw the player
Did i miss something ?
Should the visible rect of the tilemap be rendered to an image and then being drawn ?
Any help is appreciated !
Thanks in advance,
Chris
-
Control your view's position when sf::RenderWindow::Display() is called. You shouldn't reset the view every time - remove the following line:
App.SetView(App.GetDefaultView()); // Draw relative to the GUI
In the for loop, you only need to draw the tiles that are located in the current view:
const int TileSize = 15; // your tile size declared anywhere
for (int y = View.GetRect().Top / TileSize; y <= View.GetRect().Bottom / TileSize; ++y)
{
for (int x = View.GetRect().Left / TileSize; x <= View.GetRect().Right / TileSize; ++x)
{
}
}
(Probably it's better to make the limits constant and calculate them before the loop, that was just an example).
By the way: What you are doing with new leads to a massive memory leak! Try running your loop and wait how long it needs until your RAM gets exhausted.
To solve this problem, best way is not to use new here (because it is not required) and declare the variable on the stack, or place a delete statement at the end of each loop iteration to free the memory.
-
Thanks a lot, that works much better ;-)