当鼠标离开屏幕时,如何停止移动

我希望有人可以帮我解决一个小问题。

目前我有一个输入管理器连接到主摄像头,允许用户通过将鼠标移动到窗口的边缘来平移地图,但我遇到了一个小问题,我试图修复自己无济于事。

如果鼠标移出窗口,则仍然会发生平移,当我调试或使用其他应用程序时,我觉得很烦人。 因此,我希望当鼠标在游戏窗口之外时,有人可以帮助我阻止发生的移动。

这是我的输入管理器的代码。

using UnityEngine; using System.Collections; public class InputManager : MonoBehaviour { public Vector3 position = new Vector3(0,0, -10); public int boundary = 50; public int speed = 4; private int screenBoundsWidth; private int screenBoundsHeight; // Use this for initialization void Start() { screenBoundsWidth = Screen.width; screenBoundsHeight = Screen.height; } // Update is called once per frame void Update() { if (Input.mousePosition.x > screenBoundsWidth - boundary) { position.x += speed * Time.deltaTime; } if (Input.mousePosition.x  screenBoundsHeight - 10) { position.y += speed * Time.deltaTime; } if (Input.mousePosition.y < 0 + boundary) { position.y -= speed * Time.deltaTime; } Camera.mainCamera.transform.position = position; } } 

感谢您的时间。

编辑

我已经想出了一个hacky工作,但它仍然导致在窗口外部的某些位置发生移动。 我希望有人能提出更好的解决方案。

 if (Input.mousePosition.x < screenBoundsWidth && Input.mousePosition.y  screenBoundsWidth - boundary) { position.x += speed * Time.deltaTime; } } if (Input.mousePosition.x > 0 && Input.mousePosition.y > 0) { if (Input.mousePosition.x < 0 + boundary) { position.x -= speed * Time.deltaTime; } } if (Input.mousePosition.y < screenBoundsHeight && Input.mousePosition.x  screenBoundsHeight - 22) { position.y += speed * Time.deltaTime; } } if (Input.mousePosition.y > 0 && Input.mousePosition.x > 0) { if (Input.mousePosition.y < 0 + boundary) { position.y -= speed * Time.deltaTime; } } 

3点想法:

 Rect screenRect = new Rect(0,0, Screen.width, Screen.height); if (!screenRect.Contains(Input.mousePosition)) return; 

同样可以更潦草地写成:

 float mouseX = Input.MousePosition.x; float mouseY = Input.MousePosition.y; float screenX = Screen.width; float screenY = Screen.height; if (mouseX < 0 || mouseX > screenX || mouseY < 0 || mouseY > screenY) return; // your Update body 

…这与你的“hacky”解决方案(完全有效的imho)非常相似。

另一种选择是为每个屏幕边框创建4个Rect对象,然后检查鼠标是否在这些rects中。 例:

 public float boundary = 50; public float speed = 4; private Rect bottomBorder; private Rect topBorder; private Transform cameraTransform; private void Start() { cameraTransform = Camera.mainCamera.transform bottomBorder = new Rect(0, 0, Screen.width, boundary); topBorder = new Rect(0, Screen.height - boundary, Screen.width, boundary); } private void Update() { if (topBorder.Contains(Input.mousePosition)) { position.y += speed * Time.deltaTime; } if (bottomBorder.Contains(Input.mousePosition)) { position.y -= speed * Time.deltaTime; } cameraTransform.position = position; } 

这里棘手的部分是Rect坐标的Y轴指向下方,而Input.mousePosition Y指向上方……所以bottomBorder Rect必须位于顶部, topBorder必须位于底部。 左右边框不受影响。

由于Unity和各种主机操作系统的交互方式,您对鼠标光标的控制有限。 (简而言之,操作系统控制鼠标Unity只是读取它)据说你确实有一些选择。 Screen.lockCursor跳到脑海。

http://docs.unity3d.com/Documentation/ScriptReference/Screen-lockCursor.html

它不会完全符合您的要求,但它可能是一个很好的起点

Time.speed = 0;

这是你想要的吗?