- Home /
Cursor not locking in center of screen?
So I wrote a movement script that includes a cursor lock and hide function. The problem is, is that when I unlock the cursor with the Escape key, the cursor can freely move around. That is what I wanted it to do. When I re-lock the cursor, it disappears ONLY when it is on the game screen, but it can still freely move around. When it exits the game frame, it shows. It does not lock on re-lock. How would I fix this?
private bool isMouseLocked = true;
void Update () {
if (Input.GetButtonDown ("Unlock")) {
isMouseLocked = !isMouseLocked;
}
if (isMouseLocked == true) {
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
if (isMouseLocked == false) {
Cursor.lockState = CursorLockMode.None;
Cursor.visible = true;
}
}
@connorwforman I remembered facing the same problem too and ended up using Obsolete Screen.lockCursor
:/. But I just tried your code, and think I know a little more about this problem. In below script, I replace the button with "Jump", which is Space key, and it works this way. I remember reading somewhere that Escape by default escape the cursor lock status, I assume that's why Escape doesn't work. I believe there's workaround tho...
private bool is$$anonymous$$ouseLocked = true;
// Use this for initialization
void Start () {
Cursor.lockState = CursorLock$$anonymous$$ode.Locked;
}
// Update is called once per frame
void Update () {
if (Input.GetButtonDown ("Jump")) {
is$$anonymous$$ouseLocked = !is$$anonymous$$ouseLocked;
Cursor.lockState = is$$anonymous$$ouseLocked
? CursorLock$$anonymous$$ode.Locked
: CursorLock$$anonymous$$ode.None;
}
}
@connorwforman Ok so I read it here. You need to build your game. your code works in a build for me.
Answer by UnityVeris · Nov 10, 2017 at 03:19 AM
I'm making some assumptions here, but I'm pretty sure that Unity's acknowledgement of where the cursor is becomes "locked" but it doesn't actually lock where Windows registers the cursor as being.
A solution would be to look through .NET to see if you can find some cursor control functionality to import. I'm near certain I've seen something along those lines before.
Your answer
Follow this Question
Related Questions
Can you lock the cursor to specific coordinates? 0 Answers
Cursor.LockState = CursorLockMode.Locked doesn‘t works。 0 Answers
Cursor.visible doesn't hide cursor a second time. 1 Answer
Lock cursor on current position 2 Answers
Can't enable Cursor 1 Answer