2D XNA游戏鼠标点击

我有一个2D游戏,我只使用鼠标作为输入。 我怎样才能使鼠标hover在Texture2D对象上,Texture2D和鼠标光标发生变化,当点击纹理时,它移动到另一个地方。

简单地说,当我将鼠标hover在纹理2上时,我想知道如何做某事。

在XNA中,您可以使用Mouse类查询用户输入。

最简单的方法是检查每个帧的鼠标状态并做出相应的反应。 鼠标位于某个区域内吗? 显示不同的光标。 在此框架中是否按下了右键? 显示菜单。 等等

var mouseState = Mouse.GetState(); 

获取屏幕坐标(相对于左上角)的鼠标位置:

 var mousePosition = new Point(mouseState.X, mouseState.Y); 

当鼠标位于某个区域内时更改纹理:

 Rectangle area = someRectangle; // Check if the mouse position is inside the rectangle if (area.Contains(mousePosition)) { backgroundTexture = hoverTexture; } else { backgroundTexture = defaultTexture; } 

单击鼠标左键时执行某些操作:

 if (mouseState.LeftButton == ButtonState.Pressed) { // Do cool stuff here } 

请记住,您将始终拥有当前帧的信息。 因此,在点击按钮期间可能会发生很酷的事情,一旦发布就会停止。

要检查单击,您必须存储最后一帧的鼠标状态并比较更改的内容:

 // The active state from the last frame is now old lastMouseState = currentMouseState; // Get the mouse state relevant for this frame currentMouseState = Mouse.GetState(); // Recognize a single click of the left mouse button if (lastMouseState.LeftButton == ButtonState.Released && currentMouseState.LeftButton == ButtonState.Pressed) { // React to the click // ... clickOccurred = true; } 

你可以使它更高级,并与事件一起工作。 因此,您仍然可以使用上面的代码段,但不是直接包含操作代码,而是触发事件:MouseIn,MouseOver,MouseOut。 ButtonPush,ButtonPressed,ButtonRelease等

我想补充一点,鼠标点击代码可以简化,这样你就不必为它做一个变量:

 if (Mouse.GetState().LeftButton == ButtonState.Pressed) { //Write code here }