什么时候应该在SFML中使用事件



我对如何从MouseKeyboard获取输入感到困惑。例如,当我按下Mouse的按钮时,我想在Mouse的位置上画一些小点。我应该遵循哪种实施方式?

我在下面的代码中使用了window.pollEvent函数来捕捉鼠标按下事件。

#include <SFML/Graphics.hpp>
#include <iostream>
int main()
{
sf::RenderWindow window(sf::VideoMode(640,480), "Paint");
std::vector<sf::CircleShape> dots;
while (window.isOpen()) {
sf::Event event;
if (window.pollEvent(event)) {
if (event.type == sf::Event::Closed) {
window.close();
}

if (event.type == sf::Event::MouseButtonPressed) {
sf::CircleShape shape(10);
shape.setFillColor(sf::Color::Black);
shape.setPosition(event.mouseButton.x, event.mouseButton.y);
dots.push_back(shape);
}
}
window.clear(sf::Color::White);
for (auto& i : dots) {
window.draw(i);
}
window.display();
}
return 0;
}

还是我应该这样做?

#include <SFML/Graphics.hpp>
#include <iostream>
int main()
{
sf::RenderWindow window(sf::VideoMode(640,480), "Paint");
std::vector<sf::CircleShape> dots;
while (window.isOpen()) {
sf::Event event;
if (window.pollEvent(event)) {
if (event.type == sf::Event::Closed) {
window.close();
}
}
if (sf::Mouse::isButtonPressed(sf::Mouse::Left)) {
sf::CircleShape shape(10);
shape.setFillColor(sf::Color::Black);
shape.setPosition(sf::Mouse::getPosition().x, sf::Mouse::getPosition().y);
dots.push_back(shape);
}
window.clear(sf::Color::White);
for (auto& i : dots) {
window.draw(i);
}
window.display();
}
return 0;
}

如果后者是合适的,那么检查是否按下鼠标按钮的if块应该位于window.clear()之前或window.clear()window.draw()之间的哪个位置?我无法完全理解他们之间的区别。例如,SFML文档显示了后者对射击行动的实现,但我不知道为什么。谢谢

您实际上是在询问处理用户输入的两种方法:

  • 事件:处理表示事件的对象
  • 实时输入:查询输入设备的实时状态

您的第一种方法——调用sf::Window::pollEvent()——依赖于事件。它是一种异步机制;当您的代码处理该事件时,可能不会按下该按钮。如果您感兴趣的只是输入设备的状态是否发生了变化X,例如按下或释放了按钮,则通常可以进行事件处理。

您的第二种方法——调用sf::Mouse::isButtonPressed()——基于实时输入。它包括询问鼠标在调用函数时是否按下了给定的按钮。如果您只想了解输入设备的当前状态,通常可以采用这种处理用户输入的方法。


X注意,事件可以重复(例如,如果长时间按下某个键(,因此它们不一定意味着输入设备的状态发生变化。不过,您可以使用sf::Window::SetKeyRepeatEnabled()禁用此功能。

最新更新