我在Simple Directmedia层库中遇到问题。下面的代码在按下鼠标按钮时在屏幕上绘制一个块:
SDL_Event event;
while(running){
while(SDL_PollEvent(&event)){
while(event.button.state == SDL_PRESSED){
SDL_PollEvent(&event);
//where to draw
boxRect.x = event.motion.x;
boxRect.y = event.motion.y;
//Draw to screen
SDL_FillRect(display,&boxRect,boxColor);
SDL_Flip(display);
}
// ...
}
// ...
}
直到我移动鼠标,它都可以正常工作,为什么移动鼠标会导致event.button.state
错误呢?
如何同时使用两者(即在按下按钮的同时保持绘图状态)?
您的代码存在的问题是您两次调用SDL_PollEvent
(在此处记录)。如文档中所述:
如果event不为NULL,则将下一个事件从队列中删除,并存储在event指向的SDL_Event结构中。
重新安排代码,例如摆脱第二个代码SDL_PollEvent
,创建适当的流程以单击,移动,释放和从输入泵浦中提取渲染,应该会给您这样的东西:
SDL_Event Event;
while(running)
{
while(SDL_PollEvent(&Event))
{
switch(Event.type)
{
// Handle your drawing with a simple state machine:
case SDL_MOUSEBUTTONDOWN:
{
if(Event.button.button == SDL_BUTTON_LEFT)
{
if(stateMachine == Released)
{
// ... begin drawing
stateMachine = Dragging
}
}
break;
}
case SDL_MOUSEMOTION:
{
if(stateMachine == Dragging)
{
// ... update the extends of your rect
}
}
case SDL_MOUSEBUTTONUP:
{
if(Event.button.button == SDL_BUTTON_LEFT)
{
if(stateMachine != Released)
{
// ... finalize drawing... add the rect to a list? flush it?
stateMachine = Released;
}
}
}
case SDL_QUIT:
{
running = false;
break;
}
}
}
// Outside of your event pumping, update the graphics
SDL_FillRect(display,&boxRect,boxColor);
SDL_Flip(display);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句