【发布时间】:2019-07-30 21:55:13
【问题描述】:
这可能是一个菜鸟问题,但我试图让一个简单的玩家在 SFML 的 2D 网格中移动。我正在创建一个while循环来渲染正在发生的事情,我可以让它工作,但我想为网格和播放器等使用类。问题是当我创建一个名为“window”的窗口时,我不'不知道如何实现类,因为这些不知道'窗口'是什么。我希望我已经充分描述了我的问题,并且我希望对如何使这项工作进行任何回应,或者我的方法已经很糟糕并且应该更改为另一种方法。这是我的类代码的 sn-p 和未声明的窗口错误。
class myEvents {
public:
//Variables
int tSize = 40;
int tileCount = 20;
int width = tileCount * tSize;
int height = tileCount * tSize;
//Function to create a grid with RectangleShapes
void grid() {
for (int i = 0; i < tileCount; i++)
{
for (int j = 0; j < tileCount; j++)
{
sf::RectangleShape tile(sf::Vector2f(40, 40));
tile.setFillColor(sf::Color::Magenta);
tile.setPosition(i*tSize, j*tSize);
window.draw(tile); //Problem occurs here, 'window' is not declared, it is in the next function
//window.draw(tile); must execute in the loop to render a full grid
}
}
}
//Includes while loop for rendering and events. Could be written without class, but I'd still like a class for the grid and later on a player.
//So I need the window to work with my classes.
void loop() {
sf::RenderWindow window(sf::VideoMode(width, height), "Game"); //'window' declared here. Can I move this statement
//somewhere so that my funcions know where it comes from?
while (window.isOpen) {
sf::Event event;
while (window.pollEvent(e))
{
//to be further developed
}
}
}
};
【问题讨论】:
-
您可以在更高的范围内创建
window,所有类都可以访问它,但我不建议这样做。如果你有很多不同的地方试图在同一个窗口中绘制,那么追踪错误将是一个巨大的痛苦。您应该考虑使用一个单独的类来负责绘图(并且其他类可以调用) -
将窗口传递给您的班级。
标签: c++ class sfml variable-declaration