Advertisement
Guest User

Untitled

a guest
Apr 24th, 2019
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.38 KB | None | 0 0
  1. #include <SFML/Graphics.hpp>
  2. #include <iostream>
  3.  
  4.  
  5. class TileMap : public sf::Drawable, public sf::Transformable
  6. {
  7. public:
  8.  
  9. bool load(const std::string& tileset, sf::Vector2u tileSize, const int* tiles, unsigned int width, unsigned int height)
  10. {
  11. // load the tileset texture
  12. if (!m_tileset.loadFromFile(tileset))
  13. return false;
  14.  
  15. // resize the vertex array to fit the level size
  16. m_vertices.setPrimitiveType(sf::Quads);
  17. m_vertices.resize(width * height * 4);
  18.  
  19. // populate the vertex array, with one quad per tile
  20. for (unsigned int i = 0; i < width; ++i)
  21. for (unsigned int j = 0; j < height; ++j)
  22. {
  23. // get the current tile number
  24. int tileNumber = tiles[i + j * width];
  25.  
  26. // find its position in the tileset texture
  27. int tu = tileNumber % (m_tileset.getSize().x / tileSize.x);
  28. int tv = tileNumber / (m_tileset.getSize().x / tileSize.x);
  29.  
  30. // get a pointer to the current tile's quad
  31. sf::Vertex* quad = &m_vertices[(i + j * width) * 4];
  32.  
  33. // define its 4 corners
  34. quad[0].position = sf::Vector2f(i * tileSize.x, j * tileSize.y);
  35. quad[1].position = sf::Vector2f((i + 1) * tileSize.x, j * tileSize.y);
  36. quad[2].position = sf::Vector2f((i + 1) * tileSize.x, (j + 1) * tileSize.y);
  37. quad[3].position = sf::Vector2f(i * tileSize.x, (j + 1) * tileSize.y);
  38.  
  39. // define its 4 texture coordinates
  40. quad[0].texCoords = sf::Vector2f(tu * tileSize.x, tv * tileSize.y);
  41. quad[1].texCoords = sf::Vector2f((tu + 1) * tileSize.x, tv * tileSize.y);
  42. quad[2].texCoords = sf::Vector2f((tu + 1) * tileSize.x, (tv + 1) * tileSize.y);
  43. quad[3].texCoords = sf::Vector2f(tu * tileSize.x, (tv + 1) * tileSize.y);
  44. }
  45.  
  46. return true;
  47. }
  48.  
  49. private:
  50.  
  51. virtual void draw(sf::RenderTarget& target, sf::RenderStates states) const
  52. {
  53. // apply the transform
  54. states.transform *= getTransform();
  55.  
  56. // apply the tileset texture
  57. states.texture = &m_tileset;
  58.  
  59. // draw the vertex array
  60. target.draw(m_vertices, states);
  61. }
  62.  
  63. sf::VertexArray m_vertices;
  64. sf::Texture m_tileset;
  65. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement