要怎麼跟視窗互動呢?使用者在視窗上互動時,SFML 會產生事件(Event),進而接收窗口的事件,並針對發生的事件(例如:滑鼠移動、點擊,鍵盤點擊等)做相對應的處理。
sf::Event event;
while (window.pollEvent(event))
{
switch (event.type)
{
case sf::Event::Closed:
window.close();
break;
case sf::Event::KeyPressed:
// ...
break;
default:
break;
}
}
SFML 總共有以下這幾種事件:
sf::Event::Closed
sf::Event::LostFocus
, sf::Event::GainedFocus
sf::Event::Resized
event.size
event.size.width
寬event.size.height
高sf::Event::TextEntered
if (event.type == sf::Event::TextEntered)
{
if (event.text.unicode < 128)
std::cout << "ASCII character typed: " << static_cast<char>(event.text.unicode) << std::endl;
}
sf::Event::KeyPressed
, sf::Event::KeyReleased
window.setKeyRepeatEnabled(false)
if (event.type == sf::Event::KeyPressed)
{
if (event.key.code == sf::Keyboard::Escape)
{
std::cout << "the escape key was pressed" << std::endl;
std::cout << "control:" << event.key.control << std::endl;
std::cout << "alt:" << event.key.alt << std::endl;
std::cout << "shift:" << event.key.shift << std::endl;
std::cout << "system:" << event.key.system << std::endl;
}
}
sf::Event::MouseWheelScrolled
event.mouseWheelScroll
wheel
哪種滾輪
sf::Mouse::Wheel::VerticalWheel
sf::Mouse::Wheel::HorizontalWheel
delta
位移量 (正代表上、左,負相反)x
, y
座標if (event.type == sf::Event::MouseWheelScrolled)
{
if (event.mouseWheelScroll.wheel == sf::Mouse::VerticalWheel)
std::cout << "wheel type: vertical" << std::endl;
else if (event.mouseWheelScroll.wheel == sf::Mouse::HorizontalWheel)
std::cout << "wheel type: horizontal" << std::endl;
else
std::cout << "wheel type: unknown" << std::endl;
std::cout << "wheel movement: " << event.mouseWheelScroll.delta << std::endl;
std::cout << "mouse x: " << event.mouseWheelScroll.x << std::endl;
std::cout << "mouse y: " << event.mouseWheelScroll.y << std::endl;
}
sf::Event::MouseButtonPressed
, sf::Event::MouseButtonReleased
event.mouseButton
button
按鍵x
, y
座標if (event.type == sf::Event::MouseButtonPressed)
{
if (event.mouseButton.button == sf::Mouse::Right)
{
std::cout << "the right button was pressed" << std::endl;
std::cout << "mouse x: " << event.mouseButton.x << std::endl;
std::cout << "mouse y: " << event.mouseButton.y << std::endl;
}
}
sf::Event::MouseMoved
if (event.type == sf::Event::MouseMoved)
{
std::cout << "new mouse x: " << event.mouseMove.x << std::endl;
std::cout << "new mouse y: " << event.mouseMove.y << std::endl;
}
sf::Event::MouseEntered
, sf::Event::MouseMouseLeft
此外還有跟搖桿有關的事件,但這裡省略