user9657411
user9657411

Reputation:

C++ transfer SDL_renderer to a class

I am currently learning SDL2 and just managed to create a ping pong game. Some friends told me that I should start using classes for managing as an example player1 and player2. I know how to create a class but I do not understand how I would be able to pass SDL_Renderer between classes in order to render an object from within the class to the main.cpp file.

#include "SDL2/SDL.h"
#include "SDL2/SDL_render.h"
#include <iostream>
#include <windows.h>
#include <thread>
#include "player.h"

Player Player; //defining the class

const int WINDOW_WIDTH = 1280;
const int WINDOW_HEIGHT = 720;


int main(int argc, char *args[]) {

SDL_Init(SDL_INIT_EVERYTHING);

SDL_Window *window;
SDL_Renderer *renderer;

window = SDL_CreateWindow    ("Test",
                            SDL_WINDOWPOS_CENTERED,
                            SDL_WINDOWPOS_CENTERED,
                            WINDOW_WIDTH,
                            WINDOW_HEIGHT,
                            0
                            );
if (window == NULL) {
    std::cout << "Window could not load" << SDL_GetError() << std::endl;
    return 0;
}

renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
while (running) //running is a bool (true) {
    Player.draw();
}
    SDL_DestroyWindow(window);
    SDL_Quit();
    return 0;
}

What do I have to do in my player.cpp draw function in order to draw an object on the screen?

Using C++ windows, compiling the code with g++ main.cpp player.cpp -o main.exe -IC:\MinGW\i686-w64-mingw32\include -LC:\MinGW\i686-w64-mingw32\lib -lmingw32 -lSDL2main -lSDL2

Upvotes: 2

Views: 1258

Answers (1)

darclander
darclander

Reputation: 1811

In main.cpp

Player.draw(renderer)

(presuming you are using the same code as above, just pass "renderer" to the Player.draw() function.)

In player.h

class Player {
public:
    void draw(SDL_Renderer *renderer)
};

In player.cpp

void Player::draw(SDL_Renderer *renderer) {
    SDL_Rect object;
    object.x = 0;
    object.y = 0;
    object.h = 10;
    object.w = 10;
    SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);
    SDL_RenderDrawRect(renderer, &object);
    SDL_RenderFillRect(renderer, &object);
}
// will draw a white box with at position (0,0)

I believe this is a simple way to do it

Upvotes: 1

Related Questions