- Home /
How to lock the cursor without moving to the center? (С#)
HELP PLS!!! (С#) I know how to lock the cursor, but it moves to the center, but I do not need it, I need it from the same place where I clicked.
Answer by Bunny83 · Jan 12, 2018 at 11:45 AM
Unity doesn't support this because just locking in place can cause problems. Locking the cursor requires the engine to manually set the hardware cursor to the locking position every frame. However since the hardware cursor is moved asynchronously by the OS the cursor still moves between two frames. If you lock the cursor close to the game window edge it would be possible that the cursor actually leaves the game window area. If the user clicks at that moment your game will loose focus as the OS sees a click outside the window. That's the main reason why we lock to the screen center to have enough movement space in all directions.
Unity does have an alternative lock state but only for standalong targets which is CursorLockMode.Confined. Confined does not lock the cursor in place but uses functionality provided by the OS to confine the hardware cursor to a rectangle on screen. On Windows systems this is done by using the ClipCursor method.
If your target is Windows standalone you can of course manually lock the cursor to a specific position by using the Win API method SetCursorPos. However you would have the same issues i mentioned at the beginning. Usually you don't care about where you lock the cursor but you only care about where the cursor is located after you unlock the cursor. For windows standalong i would recommend to simply use Unity's normal cursor locking but in addition before locking the cursor you would remember the last cursor position (GetCursorPos) and after you released the cursor you would use SetCursorPos to move the cursor back to it's last position.
thank) I use this link text Cursor.Position = new Point(Cursor.Position.X - 50, Cursor.Position.Y - 50);
I wouldn't recommend to use System.Windows.Forms.dll. You would need to include that dll in your project just to set the cursor position. The Cursor class inside the Windows.Forms dll just wraps the Windows API function i mentioned above. The definition of GetCursorPos and SetCursorPos can be found on any pinvoke site.