gpt4 book ai didi

c++ - 释放的 SFML 鼠标按钮是垃圾邮件

转载 作者:搜寻专家 更新时间:2023-10-31 01:42:48 25 4
gpt4 key购买 nike

我正在使用 SFML 和 C++,但我遇到了一个奇怪的问题,

这是我主要的游戏更新方法

while (renderService.Window.isOpen())
{
//Poll events
sf::Event event;
while (renderService.Window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
renderService.Window.close();
running = false;
}

MouseMovment(event);
MouseClick(event);
Update();
Draw();
}

这是我的 MouseClick 方法

void Game::MouseClick(sf::Event event)
{
sf::Vector2i position = sf::Mouse::getPosition(renderService.Window);

if (event.mouseButton.button == sf::Mouse::Left && event.type == sf::Event::MouseButtonReleased)
{
std::cout << "Mouse released" << std::endl;
}
}

现在这是奇怪的部分,在我的控制台中,有时我的 cout 会被发送 10/20 次垃圾邮件,但有时它会完美地工作,我是否错误地调用了事件?

最佳答案

你做错了,假设触发了一个 MouseButtonReleased 事件并且你的轮询函数获取了它(按照注释中的数字):

while (renderService.Window.isOpen()) // 4) The loop starts again
{
//Poll events
sf::Event event;
while (renderService.Window.pollEvent(event)) // 1) Grabs the event // 5) No more events
{
if (event.type == sf::Event::Closed) // 2) Nope, it's not this one
renderService.Window.close();
running = false;
}

MouseMovment(event);
MouseClick(event); // 3) Yes, handle it // 6) Uses the unmodified event variable - undefined behavior
Update();
Draw();
}

你应该做这样的事情:

sf::Event event;

// while there are pending events...
while (window.pollEvent(event))
{
// check the type of the event...
switch (event.type)
{
// window closed
case sf::Event::Closed:
...
break;

// mouse button released
case sf::Event::MouseButtonReleased:
{
if (event.mouseButton.button == sf::Mouse::Left)
...
} break;

// we don't process other types of events
default:
break;
}

}

关于c++ - 释放的 SFML 鼠标按钮是垃圾邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26224446/

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