Mouse position with screen scrolling in SFML

霸气de小男生 提交于 2020-01-21 06:13:56

问题


Im trying to create a block placement with snap to grid. Everything is working, and in my head this should update the position of the mouse relative to the window each frame right?

sf::Vector2i position = sf::Mouse::getPosition(window.mywindow);

//get position
int xSnap = (position.x / gridWidth) * gridWidth;
int ySnap = (position.y / gridHeight) * gridHeight;

But i also have screen scrolling using

if (player.playerSprite.getPosition().x + 16 > screenDimensions.x / 2)
        position.x = player.playerSprite.getPosition().x + 16;
    else
        position.x = screenDimensions.x / 2;

    //Y
    if (player.playerSprite.getPosition().y + 16 > screenDimensions.y / 2)
        position.y = player.playerSprite.getPosition().y + 16;
    else
        position.y = screenDimensions.y / 2;

When the screen scrolls either way from its original position it doesnt update the mouse position, so for example, lets say the window size is 800x600, within that 800x600 window the position works fine, but lets say my sprite move 200px right (it starts scrolling when the sprite reaches the middle of the screen) past the original position, the object im placing using this code then appears 200px to the left of the mouse. Same happens with the y axis.

I hope that make sense


回答1:


You need to call window.mapPixelToCoords() to transform your pixel position to the coordinate system of your view.

sf::Vector2i pixel_pos = sf::Mouse::getPosition(window.mywindow);
sf::Vector2f coord_pos = window.mywindow.mapPixelToCoords(pixel_pos);

And as a general advice: Don't use public class members - mywindow and playerSprite should not be accessible from the outside.



来源:https://stackoverflow.com/questions/21554023/mouse-position-with-screen-scrolling-in-sfml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!