Applying texture to array of sprites(C++, SFML, tmxlite)

129 Views Asked by At

I'm having some difficulty applying a texture to a sprite array. I'm trying to apply the same texture to all, so that I can later setTextRect to decide which part of the texture is used as a tile in my game.

The declaration of the sprite array is in a different class and declared as follows:

sf::Sprite tileSprites[30][40]

Going line by line and debugging the stumbling block is the for loop. The response from the window is just to close and crash out with no errors.

The game crashes once the line where I try to apply the texture.

tileSprites[idx][idy].setTexture(tileMap);

  std::cout << "Creating Map... \n";
  // load the image to be used as map/the spritesheet.
  if (!tileMap.loadFromFile("Data/Maps/tilemap.png"))
  {
    std::cout << "Tilemap PNG did not load";
  }

  //load the generated tilemap
  if(!map.load("Data/Maps/test_map.tmx"))
  {
    std::cout << "TMX map file failed to load";
  }
    // access the layers in the map
    const auto& layers = map.getLayers();
    const auto layer   = layers[0]->getLayerAs<tmx::TileLayer>();
    const auto tiles   = layer.getTiles();

    int idx = 0;
    int idy = 0;

    for (int j = 0; j < tiles.size(); ++j)
    {

      idx = j / 30;
      idy = j % 30;
      tileSprites[idx][idy].setTexture(tileMap); // <-

    }
    std::cout << tiles.size();

}

Any advice would be really appreciated.

1

There are 1 best solutions below

0
Monogeon On

We can't really deduce what the problem here is due to the lack of the information or state of the timemap texture variable at its creation and where or what happens between that creation, the setting of the texture and the usage of your texture on your sprites so i'll just explain to you what most likely is happening.

sprite.setTexture() sets the texture to the sprite. it does this via pointer, thus any objects that you set the texture to that texture NEED to have access to that adress in which that texture is in. Lets for example say that the texture is local whereas the sprite is global or at least has a lifespan bigger than the texture. In this example the texture even though made correctly would make problems later on as the sprites need that texture to function further on to the end of their lifespan. What you're left is is code in which sprites know what to display only part of the time.

The most basic solutions is either make the texture where you make the sprites or make the texture a dynamic variable which you the ndelete via delete sprite.getTexture();