在 XNA 中您可以使用鼠标类 http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.input.mouse_members.aspx查询用户输入。
最简单的方法是检查每一帧的鼠标状态并做出相应的反应。鼠标位置是否在某个区域内?显示不同的光标。在此帧期间是否按下了右侧按钮?显示菜单。 ETC。
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
}
但请记住,您将始终获得以下信息current框架。因此,虽然在单击按钮期间可能会发生一些很酷的事情,但一旦释放按钮就会停止。
要检查单击,您必须存储最后一帧的鼠标状态并比较已更改的内容:
// 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 等