我有一个只使用鼠标作为输入方式的2D游戏。
当鼠标悬停在一个Texture2D对象上时,我该如何使Texture2D和鼠标指针发生变化,并且当该纹理被点击时移动到另一个位置。
简单来说,我想知道如何在悬停或点击Texture2D时执行某些操作。
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
}