Rectangle使Texture2D不可见

时间:2013-10-29 16:46:30

标签: c# xna

在我正在制作的游戏中,我有一个播放按钮,其中包含Vector2RectangleTexture2D。但不知何故,当我运行游戏时,播放按钮是不可见的,但它仍然会对鼠标碰撞/检测作出反应 这是我的代码:

    Texture2D buttonPlay;
    Rectangle buttonPlayRect;
    Vector2 buttonPlayPos;

    Point mousePosition;

    int resolutionX = ScreenManager.GraphicsDeviceMgr.PreferredBackBufferWidth;
    int resolutionY = ScreenManager.GraphicsDeviceMgr.PreferredBackBufferHeight;

    public void Initialize()
    {
        buttonPlayPos = new Vector2(resolutionX / 2 - 64, resolutionY / 2 - 64);
    }

    public override void LoadAssets()
    {
       buttonOptionsPos = new Vector2(resolutionX / 2 - 64, resolutionY / 2);

       backgroundTile = ScreenManager.ContentMgr.Load<Texture2D>("Menu/background");
       buttonOptions = ScreenManager.ContentMgr.Load<Texture2D>("Menu/optionsButton");
       buttonPlay = ScreenManager.ContentMgr.Load<Texture2D>("Menu/playButton");

       buttonPlayRect = new Rectangle((int)buttonPlayPos.X, (int)buttonPlayPos.Y, buttonPlay.Width, buttonPlay.Height);

        base.LoadAssets();
    }

    public override void Update(Microsoft.Xna.Framework.GameTime gameTime)
    {
        MouseState mState = Mouse.GetState();
        mousePosition = new Point(mState.X, mState.Y);

        base.Update(gameTime);
    }

    public override void Draw(Microsoft.Xna.Framework.GameTime gameTime)
    {
        for (int x = 0; x < 10; x++)
        {
            for (int y = 0; y < 10; y++)
            {
                ScreenManager.Sprites.Draw(backgroundTile, new Vector2(tileWidth * x, tileHeight * y), Color.White);
            }
        }

        ScreenManager.Sprites.Draw(buttonPlay, buttonPlayPos, buttonPlayRect, Color.White);
        ScreenManager.Sprites.Draw(buttonOptions, buttonOptionsPos, Color.White);

        if (buttonPlayRect.Contains(mousePosition))
        {

        }

        base.Draw(gameTime);
    }
}

我和其他项目一直有这个问题,是什么让Texture2D没有出现?提前谢谢!

1 个答案:

答案 0 :(得分:0)

当您绘制某些内容时,我建议您仅使用Vector2 positiondestinationRectangle的{​​{1}},有时会出现意外行为。
更重要的是,如果将它们作为参数传递,则没有理由设置位置并使用它来声明矩形。

作为建议,您应该在SpriteBatch.Draw方法中检查buttonPlayRect.Contains(mousePosition)Update应该只管理游戏的绘制,而不是逻辑。

<强>更新

如果您需要根据当前分辨率更改按钮的位置,可以绘制它们在每个Draw周期中声明位置

Draw

或者你可以用这种方式添加一个事件处理程序:

new Vector2(resolutionX / 2 - 64, resolutionY / 2 - 64); 方法中添加此内容:

Initialize

然后使用以下内容创建Game.Window.ClientSizeChanged += Window_ClientSizeChanged; 方法:

Window_ClientSizeChanged

当然private void Window_ClientSizeChanged(object sender, EventArgs e) { buttonPlayPos = new Vector2(resolutionX / 2 - 64, resolutionY / 2 - 64); buttonPlayRect = new Rectangle((int)buttonPlayPos.X, (int)buttonPlayPos.Y, buttonPlay.Width, buttonPlay.Height); } resolutionX必须是更新后的值。