我正在使用SFML.Net
制作游戏库,我希望能够在屏幕上放置一个50x50的磁贴。
我有窗口宽度,窗口高度,鼠标X/MouseY和基于自定义相机的偏移量。按下 WASD 时,偏移量可能会增加/减去 0.5 像素。
因此,我需要知道如何获取相对于所有这些变量的mouseX,以便我可以放置一个磁贴,使其错觉是用户按下鼠标的位置。
我已经尝试了下面的代码。
注意:Game.Instance.Scenes[Game.Instance.CurrentScene].Camera.Offset
是相机偏移。
public static float MouseX = 0;
public static float MouseY = 0;
public static float MouseXRelative = 0;
public static float MouseYRelative = 0;
public static void UpdateRelative()
{
MouseXRelative = MouseX + Game.Instance.Scenes[Game.Instance.CurrentScene].Camera.Offset.X;
MouseYRelative = MouseY + Game.Instance.Scenes[Game.Instance.CurrentScene].Camera.Offset.Y;
}
还有下面的这段代码。
注意:这将检测何时按下鼠标左键,然后创建一个游戏对象、MyGO
、**并根据鼠标X/MouseY和偏移量对其进行定位。此外,RoundTo()
是我制作的一种简单的扩展方法,用于允许四舍五入到某个数字的能力。
if (MouseHandle.LeftButtonDown)
{
float x = MouseHandle.MouseX.RoundTo(50) + Game.Instance.Scenes[Game.Instance.CurrentScene].Camera.Offset.X;
float y = MouseHandle.MouseY.RoundTo(50) + Game.Instance.Scenes[Game.Instance.CurrentScene].Camera.Offset.Y;
MyGO gm3 = new MyGO();
gm3.SetPosition(x, y);
Game.Instance.Scenes[Game.Instance.CurrentScene].Add(gm3);
}
我找到了答案。 你需要做的是使用我写的这段代码:
public static void UpdateRelative(int rt, bool doRound = false)
{
float hw = Game.Instance.Width / 2;
float hh = Game.Instance.Height / 2;
Vector2f CameraCenter = new Vector2f();
CameraCenter.X = hw;
CameraCenter.Y = hh;
float diffx;
float diffy;
MouseXRelative = CameraCenter.X - MouseX;
MouseYRelative = CameraCenter.Y - MouseY;
if (doRound)
{
MouseXRelative.RoundTo(rt);
MouseYRelative.RoundTo(rt);
}
diffx = MouseXRelative - MouseX;
diffy = MouseYRelative - MouseY;
MouseXRelative = MouseXRelative - diffx;
MouseYRelative = MouseYRelative - diffy;
}