我在Unity 3d上有一个任务,如果玩家5秒不动,屏幕中央就会出现一个弹出窗口,如果玩家移动,弹出窗口就会消失。请教我如何编写这个任务的逻辑,谢谢。
下面是代码,会检查用户的鼠标位置,看其在最近5秒内是否有移动。如果没有,那么弹出窗口就会出现。如果这里的注释很难读懂(我认为是这样),请将这段代码复制并粘贴到Visual Studio中,这样颜色将有助于区分代码和注释。
[SerializeField] GameObject popupWindow = null;
float totTime;
float timeBeforePause = 5f;
Vector3 updatedMousePosition;
private void Update()
{
// Add the time delta between frames to the totTime var
totTime += Time.deltaTime;
// Check to see if the current mouse position input is equivalent to updateMousePosition from the previous update
// If they are equivalent, this means that the user hasn't moved the mouse
if (Input.mousePosition == updatedMousePosition)
{
// Since the user hasn't moved the mouse, check to see if the total Time is greater than the timeBeforePause
if (totTime >= timeBeforePause)
{
// Set the popup window to true in order to show the window (instantiate instead it if if doesn't exist already)
popupWindow.SetActive(true);
}
}
// If the user has moved the mouse, set the totTime back to 0 in order to restart the totTime tracking variable
else
{
totTime = 0;
}
// Check to see if the popup window is visible (active)
if (popupWindow.activeSelf == true)
{
// Check to see if the user has pressed the Esc button
if (Input.GetKeyDown(KeyCode.Escape))
{
// Hide the window
popupWindow.SetActive(false);
}
}
// Update the updatedMousePosition before the next frame/update loop executes
updatedMousePosition = Input.mousePosition;
}
如果你想跟踪不同的用户输入(按键),你可以使用类似的方法。此外,你还必须在弹出窗口上实现某种按钮,允许用户在返回后从弹出窗口中退出。希望这能帮到你