0

I've tried to create a textured rectangle but when i trying to run the program it's just goes into a black screen:

#include <SDL2/SDL.h>
#include "dinoHeader.h"

int main(int argc, const char * argv[]) {
    
    if(SDL_Init(SDL_INIT_EVERYTHING) < 0){
        return 1;
    }
    
    SDL_Window* window = nullptr;
    SDL_Renderer* renderer = nullptr;
    
    
    SDL_Surface* surface = SDL_LoadBMP("./Images/smile.bmp");
    
    SDL_Texture* texture = SDL_CreateTextureFromSurface(renderer, surface);
    
    SDL_FreeSurface(surface);
    
    SDL_Rect rect;
    rect.w = 100;
    rect.h = 100;
    rect.x = (ScreenWidth / 2) - (rect.w / 2);
    rect.y = (ScreenHeight / 2) - (rect.h / 2);
    
    
    window = SDL_CreateWindow("Dino", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, ScreenWidth, ScreenHeight, SDL_WINDOW_OPENGL);
    
    renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
    
    game = true;
    
    while (game) {
        SDL_Event event;
        while(SDL_PollEvent(&event)){
            
            if(event.type == SDL_QUIT){
                game = false;
            }
            
        }
        
        SDL_SetRenderDrawColor(renderer, 0, 0, 0, SDL_ALPHA_OPAQUE);
        SDL_RenderClear(renderer);
        
        SDL_RenderCopy(renderer, texture, NULL, &rect);
        
        SDL_RenderPresent(renderer);
    }
    
    SDL_DestroyRenderer(renderer);
    SDL_DestroyTexture(texture);
    SDL_DestroyWindow(window);
    SDL_Quit();
    return 0;
}

I'm using the XCODE.

genpfault
  • 51,148
  • 11
  • 85
  • 139
  • 2
    You should add error checking to your code. SDL functions generally return `nullptr` on failure, which you can test for and call [`SDL_GetError()`](https://wiki.libsdl.org/SDL2/SDL_GetError) to get information about what went wrong. – Quentin Mar 20 '23 at 10:05
  • Common issues are: your program is running with a different working directory than your source tree, which causes the `SDL_LoadBMP` call to fail. Add error checking and find out. – Botje Mar 20 '23 at 10:14

1 Answers1

2
SDL_Renderer* renderer = nullptr;

// ...

SDL_Texture* texture = SDL_CreateTextureFromSurface(renderer, surface);

// ...

renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);

In these lines, you pass nullptr to SDL_CreateTextureFromSurface, as renderer isn't created at that point yet. You should use valid working renderer when creating a texture - so, create renderer first, only then you can use it to create textures.

As said in comments, you should check return values (in that case, your texture should be nullptr, as texture creation failed), and if they're not as expected - use SDL_GetError to inspect error message SDL have set for you.

keltar
  • 17,711
  • 2
  • 37
  • 42
  • 1
    @HoloGraphic Good general principle, declare variables and give them their initial value **at the same time**. Lessens the chance of mistakes like this. – john Mar 20 '23 at 10:59