I solved this for myself with the help of an Asset Store asset called ProMouse, which let's you set the mouse position. The script below uses that asset, toggles control with the escape key, and stops movement with Time.timeScale while cursor isn't controlled. You have to click inside the game window, then hit escape to get things going again.
// ****** code for ProMouseControl.cs
using UnityEngine;
using System.Collections;
public class ProMouseControl : MonoBehaviour {
private bool controlMouse;
void Start () {
ProMouse.Instance.SetCursorPosition(Screen.width/2, Screen.height/2);
controlMouse = true;
}
void Update () {
int mouseX = (int)ProMouse.Instance.GetLocalMousePosition().x;
int mouseY = (int)ProMouse.Instance.GetLocalMousePosition().y;
if (controlMouse) {
if ( mouseX <0) {
ProMouse.Instance.SetCursorPosition(0,mouseY);
}
if ( mouseX > Screen.width) {
ProMouse.Instance.SetCursorPosition(Screen.width,mouseY);
}
if ( mouseY <0) {
ProMouse.Instance.SetCursorPosition(mouseX,0);
}
if ( mouseY > Screen.height) {
ProMouse.Instance.SetCursorPosition(mouseX, Screen.height);
}
if (Input.GetKeyUp("escape") ) {
Time.timeScale = 0;
controlMouse = false;
}
} else if (Input.GetKeyUp("escape") ) {
Time.timeScale = 1;
ProMouse.Instance.SetCursorPosition(Screen.width/2, Screen.height/2);
controlMouse = true;
}
}
}
↧