how to get mouse position on window sfm;
Certainly! Here is an example of how to get the mouse position on a window using SFML in C++:
#include <SFML/Graphics.hpp>
int main() {
sf::RenderWindow window(sf::VideoMode(800, 600), "Mouse Position");
while (window.isOpen()) {
sf::Event event;
while (window.pollEvent(event)) {
if (event.type == sf::Event::Closed)
window.close();
}
sf::Vector2i mousePosition = sf::Mouse::getPosition(window);
std::cout << "Mouse Position: " << mousePosition.x << ", " << mousePosition.y << std::endl;
window.clear(sf::Color::White);
window.display();
}
return 0;
}
Explanation:
1. #include <SFML/Graphics.hpp>
: Includes the SFML library for graphics.
2. sf::RenderWindow window(sf::VideoMode(800, 600), "Mouse Position");
: Creates a window of size 800x600 with the title "Mouse Position".
3. while (window.isOpen()) { ... }
: Enters the main loop for handling events and updating the window until it's closed.
4. sf::Event event; while (window.pollEvent(event)) { ... }
: Polls events in the window, here specifically checking for the window close event.
5. sf::Vector2i mousePosition = sf::Mouse::getPosition(window);
: Retrieves the mouse position relative to the window.
6. std::cout << "Mouse Position: " << mousePosition.x << ", " << mousePosition.y << std::endl;
: Prints the mouse position coordinates to the console.
7. window.clear(sf::Color::White); window.display();
: Clears the window and displays the updated content.
This code creates a window and continuously displays the mouse coordinates as the mouse moves within that window.