在屏幕上移动图像

时间:2013-06-09 16:00:59

标签: c++ xcode sdl

我有一张我想要移动的图像。我的问题是图像并没有真正移动,它只是被公开,新图像加载到新位置,而旧位置仍然包含图像。

void draw_surface(int srcX, int srcY, int dstX, int dstY, int width, int height, SDL_Surface *source, SDL_Surface *destination)
{
    SDL_Rect src; 
    src.x = srcX;
    src.y = srcY;
    src.w = width;
    src.h = height;

    SDL_Rect dst;
    dst.x = dstX;
    dst.y = dstY;
    dst.w = width;
    dst.h = height;

    SDL_BlitSurface(source, &src, destination, &dst);
}

在主要功能中:

while (gameRunning)
{
    if (SDL_PollEvent(&event))
    {
        if (event.type == SDL_QUIT)
        {
            gameRunning = false;
        }
        if (event.type == SDL_KEYDOWN)
        {
            if (event.key.keysym.sym == SDLK_DOWN)
            {
                dstY += 10; //new position
            }
        }

        //apply
        apply_surface(0, 10, background, screen);
        draw_surface(srcX, srcY, dstX, dstY, width, heigth, background, screen);

    }


    //update screen
    SDL_Flip(screen);

}

这段代码出了什么问题?

1 个答案:

答案 0 :(得分:1)

  1. 您应该使用while循环来轮询事件
  2. 将绘图移到事件循环块之外是个好主意
  3. 您需要在绘制之前清除屏幕,否则旧的后台缓冲区数据仍将显示在其上
  4. Uint32 black = SDL_MapRGB(screen->format, 0, 0, 0);
    
    while (gameRunning) {
        while (SDL_PollEvent(&event)) {
            if (event.type == SDL_QUIT) {
                gameRunning = false;
            }
            if (event.type == SDL_KEYDOWN) {
                if (event.key.keysym.sym == SDLK_DOWN) {
                    dstY += 10; //new position
                }
            }
        }
        // Clear screen
        SDL_FillRect(screen, NULL, black);
    
        //apply
        apply_surface(0, 10, background, screen);
        draw_surface(srcX, srcY, dstX, dstY, width, heigth, background, screen);
    
        //update screen
        SDL_Flip(screen);
    }