c# - 纹理 2D 坐标未显示在正确的位置

标签 c# monogame

我一直在使用 SpriteBatch.Draw() 渲染一些自定义“按钮”。然而今天我意识到我应该绘制按钮的坐标与我的鼠标声称它们正在渲染的坐标不一致。这是一个问题,因为如果图形渲染关闭,则很难检测按钮是否被单击。另一种可能是鼠标坐标关闭。怎么了?

如果您需要更多信息,请询问。谢谢!

硬编码按钮位置:

    /// <summary>
    /// The x position at which the left part of the buttons on the main menu begin.
    /// </summary>
    public static readonly int ButtonX = 20;

    /// <summary>
    /// How wide the buttons are.
    /// </summary>
    public static readonly int ButtonWidth = 200;

    /// <summary>
    /// How tall the buttons are.
    /// </summary>
    public static readonly int ButtonHeight = 50;



    /// <summary>
    /// The y position of the top of the new game button.
    /// </summary>
    public static readonly int NewGameButtonY = 100;

    /// <summary>
    /// The y position of the top of the new game button.
    /// </summary>
    public static readonly int QuitButtonY = 200;

获取鼠标位置的方法:

        int x = Mouse.GetState().X;
        int y = Mouse.GetState().Y;

按钮的呈现方式:

    private static void DrawButton(MonoButton button, ref SpriteBatch spBatch)
    {
        if (button.Visible)
        {
            spBatch.Draw(button.Image, button.DrawingBounds, colorMask);
            RenderingPipe.DrawString(MainMenuLayout.MainMenuFont, button.Text, button.DrawingBounds, Alignment.Center, colorMask, ref spBatch);
        }
    }

直观地显示某事的情况: A visual display of how off something is

新游戏按钮的左上角应为 (20, 100)。

编辑:我的笔记本电脑的原始分辨率是 1920x1080,但游戏的显示分辨率肯定低于全屏模式下的分辨率。

编辑#2:我后来意识到,虽然鼠标偏移有效,但将单游戏窗口分辨率设置为显示器的 native 分辨率要容易得多。这完全解决了没有鼠标偏移的问题。

最佳答案

您的鼠标报告坐标为光标中心,而不是指针尖端。

要理解其中的原因,请考虑一个人的鼠标是另一个人的触摸屏。

您可以对按钮的点击框应用轻微的偏移,但最好只偏移从 GetState 获得的坐标并将其封装到属性中:

int offsetX = 3, offsetY = 2;
MouseState _currentState; // assume this is set by main game loop every call to Update()
int MousePositionX => _currentState.X + offsetX;
int MousePositionY => _currentState.Y + offsetY;

确切的偏移量可能取决于多种因素,包括无意的坐标转换或现有按钮组件中的偏移(检查边界框计算),因此可能需要反复试验才能立即得到解决方案。如果这样做,请确保在不同的分辨率、DPI 和 HID(人机接口(interface)设备,又名鼠标、触摸、游戏 handle 输入)下进行测试

如果确实需要动态计算,您可能会考虑查询环境以获取有关光标图标(如果有)的信息的方法。毕竟,指针并不是人们已知使用的唯一光标!

关于c# - 纹理 2D 坐标未显示在正确的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49018952/

相关文章:

c# - 将 JSON 数组转换为 XML

c# - 使用 CrystalDecisions.CrystalReports.Engine 从 Crystal Report 获取抑制条件和格式条件

c# - 为 NancyFX 正确注册 DataContext

c# - 检查 RichTextBox ScrollBar thumb 是否在滚动条的底部

xna - 如何在 MonoGame 中获取底层 Window?

c# - 设置 Monogame 窗口位置 (OSX)

c# - 适用于正常 Windows 7 开发(非 Windows 8、Android 或 iOS)的单游戏教程/演练

c# - 发布到 Facebook 群组墙并标记成员 - Graph API - C#

ios - iOS、MonoGame 截图

c# - 使用 Task.Run 运行时用户控件卡住