我无法移动我在程序中制作的矩形。运行程序时,编译器中没有错误消息。你能告诉我在键盘事件中我错过了什么。我分配给窗口的其他事件工作正常。你可以告诉我解决方案,而不是写下指令。我一直在这。感谢
#include <SDL.h>
#include <stdlib.h>
int main()
{
SDL_Window *o;
SDL_Renderer *r;
SDL_Event e;
SDL_Rect q;
int i =1;
SDL_Init(SDL_INIT_VIDEO);
o = SDL_CreateWindow("Game test",
SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED,
1024,
800,
SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE);
r = SDL_CreateRenderer(o, -1,SDL_RENDERER_ACCELERATED);
while(i)
{
while(SDL_PollEvent(&e) !=0)
{
if(e.type == SDL_QUIT)
i=0;
else if(e.type == SDL_KEYDOWN)
{
switch(e.key.keysym.sym)
{
case SDLK_ESCAPE:
case SDLK_q:
i=0;
break;
case SDLK_UP:
q.y -=10;
break;
case SDLK_DOWN:
q.y +=10;
break;
case SDLK_RIGHT:
q.x +=10;
break;
case SDLK_LEFT:
q.x -=10;
break;
}
}
}
SDL_SetRenderDrawColor(r,0,0,255,255);
SDL_RenderClear(r);
// Creating the rectangle
q.x=475;
q.y=700;
q.h=50;
q.w=50;
SDL_SetRenderDrawColor(r,0,0,0,255);
SDL_RenderFillRect(r,&q);
SDL_RenderPresent(r);
}
SDL_DestroyWindow(o);
SDL_DestroyRenderer(r);
SDL_Quit();
return 0;
}
答案 0 :(得分:2)
您没有初始化矩形对象:
byte
之前可能在事件循环中修改其值,这将导致未定义的行为:
SDL_Rect q;
然后,当您为其设置常量值时,对该对象所做的任何更改都将失效:
case SDLK_UP:
q.y -=10;
break;
因此解决方案很明确,只有在定义对象时才将常量值设置为对象。