【问题标题】:XNA Rectangle Intersection issuesXNA 矩形交点问题
【发布时间】:2013-03-25 09:02:33
【问题描述】:

我是 XNA 的新手,遇到了一个问题。 我有一个按钮类,用于游戏开始屏幕上的按钮。我想这样做,以便当鼠标单击按钮时,布尔值 isClicked 设置为 true,然后您可以对按钮执行任何操作。但是,当我编译游戏时,我似乎不能直接点击按钮的矩形(或它应该在的位置),而是必须点击它的下方或上方,每次运行游戏时都会改变。

我有这个按钮类的代码:

class cButton
{
    Texture2D texture;
    public Vector2 position;
    public Rectangle rectangle;
    public Rectangle mouseRectangle;
    public Vector2 mousePosition;





    public cButton(Texture2D newTexture, Vector2 newPosition)
    {
        texture = newTexture;
        position = newPosition;






        rectangle = new Rectangle((int)position.X, (int)position.Y, texture.Width, texture.Height);
    }

    bool down;
    public bool isClicked;

    public void Update(MouseState mouse, GameTime gameTime)
    {




        mouseRectangle = new Rectangle(mouse.X, mouse.Y, 1, 1);
        mousePosition = new Vector2(mouse.X, mouse.Y);
        if (mouseRectangle.Intersects(rectangle))
        {    
            if (mouse.LeftButton == ButtonState.Pressed)// if mouse is on button
            {
                isClicked = true;
            }
            else 
            {                   
                isClicked = false;
            }
        }
    }

    public void Draw(SpriteBatch spriteBatch)
    {
        spriteBatch.Draw(texture, position, color);
    }
}

}

游戏 1 类中用于绘制该按钮的代码:

        protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(Color.Black);

        switch (CurrentGameState)
        {
            case GameState.MainMenu:
                spriteBatch.Begin();
                spriteBatch.Draw(Content.Load<Texture2D>("Backgrounds/title"), new Rectangle(0, 0, screenWidth, screenHeight), Color.White);
                btnPlay.Draw(spriteBatch);


                spriteBatch.End(); 
                break;


        }
        base.Draw(gameTime);
    }

我在想这可能与我为它设置的屏幕分辨率有关,代码在这里:

    //Screen Adjustments
    public int screenWidth = 1280, screenHeight = 720; 

        graphics.PreferredBackBufferWidth = screenWidth;
        graphics.PreferredBackBufferHeight = screenHeight;

请帮忙,我不知道我做错了什么。

【问题讨论】:

  • 屏幕分辨率变化不会影响 XNA 中鼠标的输入,触摸输入会受到设置后缓冲的影响。

标签: c# xna intersect


【解决方案1】:

I believe this question ought to help you out. :)

基本上,您创建一个点结构,并在按钮的矩形中调用 Contains 方法。它会告诉你点击是否在按钮上。

【讨论】:

  • 感谢您的快速回复。明天我会对此进行测试并回复您。
  • 这种方式有时有效,但有时无效。对我来说,它比以前的方法更有效,但有时它仍然不起作用,并且给我与上面相同的错误,我必须单击实际纹理周围的某个位置才能使 bool isClicked 等于 true。编辑:我还发现每次发生这种情况时鼠标的实际位置都会偏离一点,也许与此有关?
  • 您是否设法找出导致鼠标位置关闭的原因?
  • 我认为鼠标位置关闭可能是由于它的窗口句柄。我将这行代码 Mouse.WindowHandle = Window.Handle; 添加到我的 game1.cs 中,现在它似乎可以工作了。
猜你喜欢
  • 2011-08-03
  • 1970-01-01
  • 1970-01-01
  • 2011-05-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多