C# XNA矩形相交问题
我是XNA的新手,遇到了一个问题。 我有一个button类,我正在使用它作为游戏开始屏幕上的按钮。我想这样做,当鼠标点击按钮时,一个布尔值isClicked被设置为true,然后你可以用这个按钮做任何你想做的事情。然而,当我编译游戏时,我似乎不能直接点击按钮的矩形(或它应该在哪里),但我必须点击它的下方或上方,每次运行游戏时都会发生变化 我有button类的代码:C# XNA矩形相交问题,c#,xna,intersect,C#,Xna,Intersect,我是XNA的新手,遇到了一个问题。 我有一个button类,我正在使用它作为游戏开始屏幕上的按钮。我想这样做,当鼠标点击按钮时,一个布尔值isClicked被设置为true,然后你可以用这个按钮做任何你想做的事情。然而,当我编译游戏时,我似乎不能直接点击按钮的矩形(或它应该在哪里),但我必须点击它的下方或上方,每次运行游戏时都会发生变化 我有button类的代码: class cButton { Texture2D texture; public Vector2 position
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);
}
}
}
在game 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);
}
请帮忙,我不知道我做错了什么。
基本上,创建一个点结构,并在按钮的矩形中调用Contains方法。它会告诉你是否点击了按钮 谢谢你的快速回复。我明天会测试一下,然后再给你回复。这种方法有时有效,但有时无效。对我来说,它比前一种方法更有效,但有时它仍然不起作用,并给我与上面相同的错误,我必须单击实际纹理周围的某个位置,以使bool isClicked等于true。编辑:我还发现,每次这种情况发生时,鼠标的实际位置都会关闭一点,也许这与此有关?你是否找到了导致鼠标位置关闭的原因?我认为鼠标位置关闭可能是因为它的窗口手柄。我添加了这行代码
Mouse.WindowHandle=Window.Handle
到my game1.cs,它现在似乎可以工作了。屏幕分辨率的更改不会影响XNA中鼠标的输入,触摸输入会受到设置backbuffer的影响。
//Screen Adjustments
public int screenWidth = 1280, screenHeight = 720;
graphics.PreferredBackBufferWidth = screenWidth;
graphics.PreferredBackBufferHeight = screenHeight;