Mouse position with screen scrolling in SFML(SFML 中屏幕滚动的鼠标位置)
问题描述
我正在尝试使用对齐网格创建块放置.一切正常,在我的脑海中,这应该更新鼠标相对于窗口的位置,对吗?
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;
但我也有屏幕滚动使用
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;
当屏幕从其原始位置滚动时,它不会更新鼠标位置,例如,假设窗口大小为 800x600,在该 800x600 窗口内该位置工作正常,但假设我的精灵向右移动 200 像素(当精灵到达屏幕中间时它开始滚动)超过原始位置,使用此代码放置的对象然后出现在鼠标左侧 200 像素处.y 轴也是如此.
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.
我希望这是有道理的
推荐答案
您需要调用 window.mapPixelToCoords() 将像素位置转换为视图的坐标系.
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);
作为一般建议:不要使用公共类成员 - mywindow 和 playerSprite 不应从外部访问.
And as a general advice: Don't use public class members - mywindow and playerSprite should not be accessible from the outside.
这篇关于SFML 中屏幕滚动的鼠标位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:SFML 中屏幕滚动的鼠标位置
				
        
 
            
        基础教程推荐
- 如何通过C程序打开命令提示符Cmd 2022-12-09
 - 如何在 C++ 中初始化静态常量成员? 2022-01-01
 - 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
 - 如何检查GTK+3.0中的小部件类型? 2022-11-30
 - 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
 - 在 C++ 中计算滚动/移动平均值 2021-01-01
 - C++结构和函数声明。为什么它不能编译? 2022-11-07
 - 我有静态或动态 boost 库吗? 2021-01-01
 - 这个宏可以转换成函数吗? 2022-01-01
 - 常量变量在标题中不起作用 2021-01-01
 
    	
    	
    	
    	
    	
    	
    	
    	
						
						
						
						
						
				
				
				
				