I have a question. I have been learning SFML and know C++ pretty well, But one thing I have never understood too well was using objects in different classes.
I've heard that you make a reference to the object and then use it in other classes but I don't understand how to do this with constructors because when I try the, constructor wont get called, But the program runs. What I'm mainly trying to do is use sf::RenderWindow in my other classes. I'm sorry if you get mad but this is something that never gets explained well.
You can use a class just like any other type. So if you know how to have a class own a data member of type int, you know how to make it own an object of a class type.
Are you trying to basically make a base Game class that handles the window and game flow?
If so here is a minor example of using sf::RenderWindow in a class which can give you a idea. Basically this is just taking the main game loop out of the main file and putting it inside of a class.
#include <SFML/Graphics.hpp>
class Game
{
public:
Game();
void run(); // Runs the game
void processEvents(); // This is where event handling goes
void update(sf::Time deltaTime); // Update logic here
void render(); // Render stuff here.
private:
void handlePlayerInput(sf::Keyboard::Key key, bool isPressed); // Helper for processing player input
private:
sf::RenderWindow window;
}
Game::Game() : window(sf::VideoMode(640, 480), "SFML Application")
{
}
void Game::run()
{
// Main game loop here.
// I left out managing deltatime and fps
while (window.isOpen())
{
processEvents();
update(); // You should pass deltatime to the update function
render();
}
}
void Game::processEvents()
{
// Handle events here
sf::Event event;
while (window.pollEvent(event))
{
switch(event)
{
case sf::Event::Closed:
window.close();
break;
case sf::Event::KeyPressed:
handlePlayerInput(event.key.code, true);
break;
case sf::Event::KeyReleased:
handlePlayerInput(event.key.code, false);
break;
}
}
}
void Game::update(sf::Time deltaTime)
{
// Update your game logic here.
// Again remember to include deltatime
}
void Game::render()
{
window.clear();
window.displayer();
}
void Game::handlePlayerInput(sf::Keyboard::Key key, bool isPressed)
{
// Handle key presses here.
}
If you want more info we might need to know exactly what you are trying to do with your sf::RenderWindow objects in order to help.