Search code examples
c++sdl2d-games

Surface dissapears when I use SDL_RECT


Im trying to create a class that contains the info of my game's SHIP (image and position at the moment), everything compiles as I expected it but if I use the SDL_Rect variable I created inside my ship as an argument in the SDL_blitsurface method, the ship does not appear.

Here's my code:

main.cpp

int main()
{
    init();
    Ship ship;
    ship.alive();
    Background bg;
    SDL_BlitSurface(bg.bg,NULL,screen,NULL);
    printf("%i",ship.rect.y);
    SDL_BlitSurface(ship.img,&ship.rect,screen,NULL);
    SDL_UpdateWindowSurface(window);
    SDL_Delay(5000);
    return 0;
}

Ship.cpp

Ship::Ship(){
    std::string path = "img/arwing2.png";
    x = 50;
    y = 50;
    rect.x = x;
    rect.y = y;
    rect.w = 300;
    rect.y = 300;
    img = IMG_Load(path.c_str());
    if(img == NULL){
        printf("Unable to load image");
    }
    printf("Hey!!");
}


void Ship::alive(){
    printf("I'm alive!");
}

Any idea of what I'm doing wrong? this is what I want enter image description here

This is what I gete


Solution

  • In your code, you have provided the source rect.

    This means that it is cutting your image to show only the pixels from (x,y) inside your image and extending by (w,h).

    What you probably wanted to provide the destination rect to tell SDL_BlitSurface where to draw it, i.e. (x,y) from inside the screen. As follows:

    SDL_BlitSurface(ship.img, NULL, screen, &ship.rect);
                              ^(src)        ^(dest)