I have a game called Galactic Neon, an Asteroids-like twin-stick shooter that uses the cursor as an aiming reticle. One annoying problem I have with the linked webplayer is that I accidentally click outside of the webplayer quite frequently. Is there a way to prevent this from happening? From what I understood, Screen.lockCursor
only locks the mouse to the center of the webplayer, which is not what I want.
Thanks to @merry_christmas, I now know it’s not possible. Darn.
Edit: I believe starting with Unity 5, it is now possible to confine the mouse to the window of the application.
The behavior is not consistent across platforms, but at least for Windows 10, the follow code works wonders:
Cursor.lockState = CursorLockMode.Confined;
I am not certain this works with WebGL yet.
The usual solution in such a case is to use a virtual mouse cursor. So you simply lock and hide the cursor (this also works in WebGL) and simply use your own graphic / image as cursor. This you can move around by reading the mouse deltas with the Input class
var delta = new Vector3(Input.GetAxis("Mouse X"), -Input.GetAxis("Mouse Y"));
yourCursorObject.transform.position += delta;
Of course you have to clamp the object position manually so it stays within your desired area. You can also make it wraparound if you like. It’s a virtual cursor so you can do what you want. Of course you would need to use the object position as mouse position and not Input.mousePosition. There are many ways how to display such a cursor. The usual way is probably to use Unity’s GUI system but a GUITexture would work as well.
Many games use virtual mouse cursors but only for visual reasons. They also hide the hardware cursor and simply display a virtual cursor at the actual cursor position. However using a pure virtual cursor has many advantages. You can set the position of the cursor to any point inside your game, even in WebGL builds. You also can easily freeze the cursor by not applying the delta each frame.