This might be a noob question, but I'm trying to make a simple player move in a 2D-grid in SFML. I'm creating a while loop for rendering what is happening, and I can get it to work, but I want to use classes for the grid and players etc. The problem is that when I create a window called 'window', I don't know how to implement classes since these don't know what the 'window' is. I hope I have described my problem sufficiently, and I would like any respons on how to make this work or if my method of doing it is already bad and should be changed for another method. Here is a snippet of my code for the class and the undeclared window error.
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
}
}
}
};
Well an easy thing for the window you can do is to create a class and add the window in it, then include the .h where the class is as you've set the sf::window in the public section. Now I will show you how you can use it
we've got an .h file named window.h (you can name it whatever is comfortable for you)
#include <SFML/Grpahics.hpp>
class window
{
public:
sf::RenderWindow window;
}
and you have the main.cpp(or whatever file you want)
#include "window.h"
window w;
int main()
{
w.window.create(sf::VideoMode(800,600),"Title");
}
the int main() can be whatever function you want it just has to be called as soon as possible so the window will show. I hope this helps you with your problem =) [EDID]: As the "sf::RenderWindow window" is public every file that has the header with the public "sf::RenderWindow window" can use the window as it is not private. I think you know that but in any case to add it.