抱歉,英语不是我的母语,所以如果问题不清楚,请告诉我。 所以我有一个单元对象、一个地图结构和一个地图管理器;重要的是这些:
细胞.hpp
#pragma once
#include <SFML\Graphics.hpp>
enum class CellState
{
selected,
notSelected,
selectable
};
struct Cell : sf::RectangleShape
{
private:
CellState m_state = CellState::notSelected;
public:
Cell(const CellState& state)
: m_state(state)
{
}
Cell()
{
m_state = CellState::notSelected;
}
void setCellState(CellState state)
{
m_state = state;
}
};
地图.hpp
#pragma once
#include <SFML\Graphics.hpp>
#include "Cell.hpp"
struct Map
{
private:
static const int m_sizeX = 8;
static const int m_sizeY = 8;
Cell m_map[m_sizeX][m_sizeY];
public:
static const int m_cellSize = 64;
Map()
{
Cell cell(CellState::notSelected);
for (size_t y = 0; y < m_sizeY; y++)
{
for (size_t x = 0; x < m_sizeX; x++)
{
m_map[x][y] = cell;
}
}
}
bool isValidCoord(sf::Vector2i cellCoord)
{
if (cellCoord.x < 0 || cellCoord.y < 0 || cellCoord.x > m_sizeX - 1 || cellCoord.y > m_sizeY - 1)
{
return false;
}
return true;
}
Cell getCellAt(int x, int y)
{
return m_map[x][y];
}
};
mapManager.hpp
#pragma once
#include <SFML\Graphics.hpp>
#include "Map.hpp"
class MapManager
{
public:
MapManager();
void drawMap(sf::RenderWindow &window);
sf::Vector2i mouseCoordToGridCoord(sf::Vector2i mouseCoord);
void selectCell(sf::Vector2i cellCoord);
void deselectCell(sf::Vector2i cellCoord);
bool isValidCoord(sf::Vector2i cellCoord);
sf::Vector2i getLastSelectedCell();
private:
sf::Vector2i m_lastSelectedCell;
public:
Map map;
};
地图管理器.cpp
#include "headers\map\MapManager.hpp"
MapManager::MapManager()
{
}
void MapManager::drawMap(sf::RenderWindow &window)
{
for (size_t y = 0; y < sizeY; y++)
{
for (size_t x = 0; x < sizeX; x++)
{
Cell cell = map.getCellAt(x, y);
switch (cell.getCellState())
{
case CellState::selected:
{
cell.setFillColor(sf::Color::Yellow);
}break;
case CellState::notSelected:
{
cell.setFillColor(sf::Color::Black);
}break;
}
cell.setPosition(map.m_cellSize * x, map.m_cellSize * y);
window.draw(cell);
}
}
}
sf::Vector2i MapManager::mouseCoordToGridCoord(sf::Vector2i mouseCoord)
{
return mouseCoord / map.m_cellSize;
}
void MapManager::selectCell(sf::Vector2i cellCoord)
{
map.getCellAt(cellCoord).setCellState(CellState::selected);
m_lastSelectedCell = cellCoord;
}
void MapManager::deselectCell(sf::Vector2i cellCoord)
{
map.getCellAt(cellCoord).setCellState(CellState::notSelected);
}
bool MapManager::isValidCoord(sf::Vector2i cellCoord)
{
return map.isValidCoord(cellCoord);
}
sf::Vector2i MapManager::getLastSelectedCell()
{
return m_lastSelectedCell;
}
我想要的是,当我单击一个单元格时,该单元格会变成黄色,但由于某种原因,即使
map.getCellAt(cellCoord).setCellState(CellState::selected);
似乎改变了 m_state
的值,但没有改变
我尝试使用调试器来理解原因,但我无法理解它发生的原因。 我希望我写的很清楚。
您应该更改 getCellAt 的返回类型:
Cell& getCellAt(int x, int y)
{
return m_map[x][y];
}
这将返回对单元格的引用,而不是其副本。