c# XNA鼠标位置

本文关键字:位置 鼠标 XNA | 更新日期: 2023-09-27 18:12:36

我在XNA中有一些鼠标坐标问题- 0x0任意靠近(但不是在)屏幕的左上角。

我现在在窗口模式下运行游戏,但坐标是基于屏幕的,而不是游戏窗口(尽管XNA文档告诉我应该是这样)

提前感谢!

代码如下:

namespace TheGame
{
   class Mousey
   {
      static public Vector2 pos;
      static private Texture2D tex;
      static public MouseState mouseState;
      static public MouseState previousState;
      //static public Mousey()
      //{
      //}
      static public void Update()
      {
         previousState = mouseState;
         mouseState = Mouse.GetState(); //Needed to find the most current mouse states.
         pos.X = mouseState.X; //Change x pos to mouseX
         pos.Y = mouseState.Y; //Change y pos to mouseY
      }
      //Drawing function to be called in the main Draw function.
      static public void LoadContent(ContentManager thecontent)
      {
         tex = thecontent.Load<Texture2D>("mousey");
      }
      static public void Draw(SpriteBatch batch) //SpriteBatch to use.
      {
         batch.Draw(tex, pos, Color.White); //Draw it using the batch.
      }
      static public bool LBP()
      {
          if (mouseState.LeftButton == ButtonState.Pressed && previousState.LeftButton ==                      ButtonState.Released)
          {
              return true; 
          }
          else 
          { 
              return false; 
          }
      }   
   }
}

c# XNA鼠标位置

In game.cs:

//sets the windows mouse handle to client bounds handle
Mouse.WindowHandle = Window.Handle;
private IntPtr intPtr;
    public MouseControle(int w, int h, IntPtr intPtr)
    {
        screenwidth = w;
        screenheight = h;
        this.intPtr = intPtr;
        Mouse.WindowHandle = intPtr;
    }

这对我有用;)

为了使用它,我使用这个类将它添加到我的游戏组件中:
mouse = new MouseControle(((Game1)Game).setscreen.width, 
((Game1)Game).setscreen.height, 
((Game1)Game).Window.Handle);
D

你试过更简单的方法吗?

protected override void Draw( GameTime gameTime )
{
    graphics.GraphicsDevice.Clear( Color.CornflowerBlue );
    base.Draw( gameTime );
    MouseState current_mouse = Mouse.GetState();
    Vector2 pos = new Vector2(current_mouse.X, current_mouse.Y);
    batch.Draw(tex, pos, Color.White);
}
在绘制和更新之间可能会有一些时间,由于XNA的计时工作方式,也许这是感知像素偏移的原因?

…你确定你正确地"配置"了你的雪碧批次吗?坐标是相对于游戏窗口的,所以文档中是这么说的。

还有一件事:为什么要使用静态字段?我真的不喜欢这个选择,一个反模式。使用类字段,而不是静态字段。

也……我猜你画的是鼠标图标,对吗?考虑到XNA从指定的点开始绘制纹理,您确定纹理形状良好,左上角点作为鼠标箭头的终点吗?

我找到了一个很好的例子,你可能会喜欢:http://azerdark.wordpress.com/2009/07/08/displaying-cursor-xna/

还可以考虑使用IsMouseVisible = true;

启用和禁用普通windows操作系统鼠标光标

你的draw调用根本没有抵消纹理。如果图像的"指针"部分不在纹理的0,0位置(左上角),则定位会出现偏差。

添加一个Console.WriteLine(pos);到你的更新,看看它正在绘制的位置。记得在调试后删除它,因为writeline会降低性能。

尝试重载的SpriteBatch.Draw()调用"origin"中的哪个因子,它可以让你决定纹理的哪个点应该在该位置绘制。在下面的代码中,根据纹理的绘制方式调整矢量2。

batch.Draw(tex, pos, null, Color.White, 0.0f, new Vector2(10, 10), SpriteEffects.None, 0.0f);