2D XNA游戏鼠标点击

Ahm*_*azy 12 c# xna

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

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

Luc*_*ius 32

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

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

var mouseState = Mouse.GetState();
Run Code Online (Sandbox Code Playgroud)

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

var mousePosition = new Point(mouseState.X, mouseState.Y);
Run Code Online (Sandbox Code Playgroud)

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

Rectangle area = someRectangle;

// Check if the mouse position is inside the rectangle
if (area.Contains(mousePosition))
{
    backgroundTexture = hoverTexture;
}
else
{
    backgroundTexture = defaultTexture;
}
Run Code Online (Sandbox Code Playgroud)

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

if (mouseState.LeftButton == ButtonState.Pressed)
{
    // Do cool stuff here
}
Run Code Online (Sandbox Code Playgroud)

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

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

// 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;
}
Run Code Online (Sandbox Code Playgroud)

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