Question

I am trying to make my first pong game in c++ with sfml but I have some problems when I try to call the window.draw() function I think my code will explain the most.

This is my Game.h

#pragma once
#include <SFML/Graphics.hpp>

class Game
{
public:
    Game();
    void                run();
private:
    void                processEvents();
    void                update();
    void                render();
    sf::RenderWindow    mWindow;
};

My game.cpp

#pragma once
#include "Game.h"
#include "Paddle.h"

Game::Game()
    : mWindow(sf::VideoMode(640,480), "Pong")
{

}

void Game::run()
{
    while (mWindow.isOpen())
    {
        processEvents();
        update();
        render();
    }
}

void Game::processEvents()
{
    sf::Event event;
    while(mWindow.pollEvent(event))
    {
        if(event.type == sf::Event::Closed)
            mWindow.close();
    }
}

void Game::render()
{
    mWindow.clear();
    mWindow.draw(Paddle::player1);
    mWindow.display();
}

void Game::update()
{

}

my Paddle.h and paddle.cpp

#pragma once
#include <SFML/Graphics.hpp>
class Paddle
{
public:
    Paddle(int width, int height);
    sf::RectangleShape player1(sf::Vector2f(int width,int height));
    sf::RectangleShape player2(sf::Vector2f(int width,int height));
private:

};

My paddle.h

#include "Paddle.h"


Paddle::Paddle(int width,int height)
{

}

My main.cpp

#include "Game.h"
#include "Paddle.h"
int main()
{
    Game game;
    Paddle player1(10,60);
    Paddle player2(10,60);
    game.run();
}

That was all my code. The problem is that I don't know how to draw the paddles in my Game.cpp I think I should use some sort of pointers or reference-argument. When I do it like this:

void Game::render()
{
    mWindow.clear();
    mWindow.draw(Paddle::player1);
    mWindow.display();
} 

I get an error. How do I solve this?

Was it helpful?

Solution

You need something like

class Game
{
public:
    Game(Paddle & p1, Paddle & p2);
...
private:
...
    Paddle & mP1;
    Paddle & mP2;
};

Game::Game(Paddle & p1, Paddle & p2)
    : mWindow(sf::VideoMode(640,480), "Pong"),
      mP1(p1), mP2(p2)
{
}

void Game::render()
{
    mWindow.clear();
    mWindow.draw(mP1);
    mWindow.display();
}

int main()
{
    Paddle player1(10,60);
    Paddle player2(10,60);
    Game game(player1, player1);
    game.run();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top