这可能是一个菜鸟问题,但我正在尝试让一个简单的播放器在SFML中的2D网格中移动。我正在创建一个while循环来渲染正在发生的事情,并且可以使其正常工作,但是我想对网格和播放器等使用类。问题是当我创建一个名为“ window”的窗口时,我不会不知道如何实现类,因为这些不知道什么是“窗口”。我希望我已经充分描述了我的问题,并且希望对如何进行这项工作或我的执行方法已经很糟糕并且应该更改为另一种方法做出任何回应。这是我的类代码片段和未声明的窗口错误。
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
}
}
}
};
答案 0 :(得分:1)
尝试使窗口成为类成员:
class myEvents {
public:
//Variables
int tSize = 40;
int tileCount = 20;
int width = tileCount * tSize;
int height = tileCount * tSize;
sf::RenderWindow window{sf::VideoMode(width, height), "Game"};
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);
}
}
}
void loop() {
while (window.isOpen) {
sf::Event event;
while (window.pollEvent(e))
{
//to be further developed
}
}
}
};
或者,将窗口绕过:
class myEvents {
public:
//Variables
int tSize = 40;
int tileCount = 20;
int width = tileCount * tSize;
int height = tileCount * tSize;
void grid(sf::RenderWindow& window) {
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);
}
}
}
void loop() {
sf::RenderWindow window{sf::VideoMode(width, height), "Game"};
while (window.isOpen) {
sf::Event event;
while (window.pollEvent(e))
{
//to be further developed
// call grid(window)
}
}
}
};
答案 1 :(得分:0)
对于窗口来说,一件容易的事就是创建一个类,然后 在其中添加窗口,然后在已在公共部分设置sf :: window的位置将.h包含在类中。现在,我将向您展示如何使用它
我们有一个名为window.h的.h文件(您可以根据自己的喜好命名)
#include <SFML/Grpahics.hpp>
class window
{
public:
sf::RenderWindow window;
}
并且您拥有main.cpp(或所需的任何文件)
#include "window.h"
window w;
int main()
{
w.window.create(sf::VideoMode(800,600),"Title");
}
int main()可以是您想要的任何函数 尽快调用,以便显示窗口。 我希望这可以帮助您解决问题=) [EDID]: 因为“ sf :: RenderWindow窗口”是公共的,所以每个带有公共“ sf :: RenderWindow窗口”标头的文件都可以使用该窗口,因为它不是私有的。我想您知道,但无论如何都要添加它。