我创建了一个类来加载效果很好的tilemap。在我的应用程序中,我想在单击时更改此地图中的图块,我做了一个程序,该程序可以知道单击了哪个图块,但找不到在tilemap中更改图块的正确方法。
TileMap.h:
#ifndef TILEMAP_H
#define TILEMAP_H
#include <SFML/Graphics.hpp>
#include <iostream>
#include <cstring>
class TileMap : public sf::Drawable, public sf::Transformable
{
public:
void createTileMap(std::string path, int tilesize, int tiles);
void changeTile(int f, char c);
virtual void draw(sf::RenderTarget &target, sf::RenderStates states) const;
private:
int index = 0;
char blocks[3364];
sf::Texture tileset;
sf::VertexArray vertices;
};
#endif
TileMap.cpp:
void TileMap::createTileMap(std::string path, int tilesize, int tiles)
{
//load the texture of tiles.
if(!tileset.loadFromFile(path)) std::cout << "Unable to open map" << std::endl;
vertices.setPrimitiveType(sf::Quads);
vertices.resize(tiles * tiles * 4);
for(int i = 0; i < tiles; ++i)
{
for(int j = 0; j < tiles; ++j)
{
sf::Vertex* quad = &vertices[(i + j * tiles) * 4];
quad[0].position = sf::Vector2f(j * tilesize, i * tilesize);
quad[1].position = sf::Vector2f(j * tilesize + tilesize, i * tilesize);
quad[2].position = sf::Vector2f(j * tilesize + tilesize, i * tilesize + tilesize);
quad[3].position = sf::Vector2f(j * tilesize, i * tilesize + tilesize);
if(blocks[index] == 'G') ///GRASS
{
quad[0].texCoords = sf::Vector2f(0, 0);
quad[1].texCoords = sf::Vector2f(50, 0);
quad[2].texCoords = sf::Vector2f(50, 50);
quad[3].texCoords = sf::Vector2f(0, 50);
}
index++;
void TileMap::draw(sf::RenderTarget& target, sf::RenderStates states) const
{
states.transform *= getTransform();
states.texture = &tileset;
target.draw(vertices, states);
}
void TileMap::changeTile(int f, char c)
{ //this function is supposed to change a tile
blocks[f] = c;
}
我该怎么办?