gpt4 book ai didi

c - SDL - 为什么移动鼠标会改变按钮状态?

转载 作者:太空宇宙 更新时间:2023-11-04 07:26:13 25 4
gpt4 key购买 nike

我在使用 Simple Directmedia Layer 库时遇到问题。按下鼠标按钮时,以下代码在屏幕上绘制一个 block :

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(已记录 here)。如文档中所述:

If event is not NULL, the next event is removed from the queue and stored in the SDL_Event structure pointed to by 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);
}

关于c - SDL - 为什么移动鼠标会改变按钮状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18124398/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com