XNA矩形交叉点问题

时间:2013-03-25 00:19:47

标签: c# xna intersect

我是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;

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

1 个答案:

答案 0 :(得分:1)

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

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