- Home /
How to lock cursor in WebGL
Hello,
At this point I am quite desperate so I decided to seek help personally. I have this (project) and in my newest build, when I looked around it would snap back ( probably after the cursor reached an edge of the screen) which is weird because that never occured before and I am using unity first person controller. Afterwards I tried to search trough the forum to see what the problem is. Ended up finding this code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MouseLock : MonoBehaviour
{
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(0))
{
//Mouse lock and confine
Cursor.visible = false;
Cursor.lockState = CursorLockMode.Locked;
Cursor.lockState = CursorLockMode.Confined;
}
if (Input.GetKeyDown("1"))
{
//and to unlock it is this:
Cursor.lockState = CursorLockMode.None;
Cursor.visible = true;
}
}
}
that I have tried implementing first just by adding it as a component onto the first person camera then the controller. None of that worked so I tried to insert it into the code of the controller, but that didn't help either. And now I am clueless of what to try next.
Any help would be greatly appreciated since I am quite a noob and made the whole project just by tweaking stuff from tutorial videos.
Also to see the original problem see the website after I changed the code it didn't even snap back it didn't even allow me to move any further from which I conclude, that the cursors just turns invisible but it doesn't lock. In my unity editor everything works fine.
Answer by hunvee3 · Mar 21, 2018 at 01:26 AM
I'm not sure about this since I haven't tested yet but the manual states that for security reasons browsers don't allow any events related to cursor locking that it can't prove came from a user initiated event. By the time you call input.getkeydown it's too late and the browser ignores it. The manual says that cursor locking should be done on up events so you should use getkeyup instead of getkeyup. Hope this helps
I don't know from which documentation you got the fact that mouse/key up events where the way to go, straight from the actual documentation:
you should trigger cursor locking or full-screen requests on mouse/key down events, ins$$anonymous$$d of mouse/key up events
Your answer
Follow this Question
Related Questions
Mouse won't unlock in WebGL build but does in the editor 1 Answer
Why does my cursor image have artifacts in WebGL? 2 Answers
Alt+Tab pointer problem 0 Answers
Cursor not locking in center of screen? 1 Answer
SetCursor WebGL doesn't work 1 Answer