在SDL2中使用方法来在按键时移动矩形,可以按照以下步骤进行:
下面是一个简单的示例代码,展示了在SDL2中使用方法在按键时移动矩形:
#include <SDL2/SDL.h>
int main() {
SDL_Init(SDL_INIT_VIDEO);
SDL_Window* window = SDL_CreateWindow("Moving Rectangle", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 640, 480, 0);
SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, 0);
SDL_Rect rect = { 100, 100, 50, 50 };
bool quit = false;
SDL_Event event;
while (!quit) {
while (SDL_PollEvent(&event)) {
if (event.type == SDL_QUIT) {
quit = true;
}
else if (event.type == SDL_KEYDOWN) {
switch (event.key.keysym.sym) {
case SDLK_UP:
rect.y -= 10;
break;
case SDLK_DOWN:
rect.y += 10;
break;
case SDLK_LEFT:
rect.x -= 10;
break;
case SDLK_RIGHT:
rect.x += 10;
break;
default:
break;
}
}
}
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
SDL_RenderClear(renderer);
SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);
SDL_RenderFillRect(renderer, &rect);
SDL_RenderPresent(renderer);
}
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
return 0;
}
在上述示例代码中,按下向上、向下、向左、向右箭头键时,矩形对象将相应地进行移动。使用SDL_Rect结构体来定义矩形的位置和尺寸,使用SDL_RenderFillRect()函数将矩形渲染到渲染器中,通过修改矩形的坐标来实现移动。
领取专属 10元无门槛券
手把手带您无忧上云