c++ - 在屏幕上移动图像

标签 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. 您应该使用while 循环来轮询事件
  2. 将绘图移到事件循环 block 之外是个好主意
  3. 您需要在绘制之前清空屏幕,否则旧的后台缓冲区数据仍会保留在屏幕上
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);
}

关于c++ - 在屏幕上移动图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17011451/

相关文章:

c++ - 对映射中的lower_bound和upper_bound

ios - 检查定时器是否正在运行

c++ - 应用分发

cmake - 如何安装 SDL 开发库以便 CMake 可以找到它

c++ - 如何在 OGRE 中使用 SDL?

c++ - 识别设置项

c++ - 当需要基类作为参数时无法传递子类的 vector

c++ - 指向类成员函数的指针类型转换错误

mysql - 免费的 SQLite GUI 工具?

objective-c - plist 文件中的 Xcode 4.6 本地化