Search Unity

  1. Looking for a job or to hire someone for a project? Check out the re-opened job forums.
    Dismiss Notice
  2. Unity 2020 LTS & Unity 2021.1 have been released.
    Dismiss Notice
  3. Good news ✨ We have more Unite Now videos available for you to watch on-demand! Come check them out and ask our experts any questions!
    Dismiss Notice

CursorLockMode.Locked causes MouseLook to jump in 2D

Discussion in '2D' started by Darkolos, Feb 18, 2021.

  1. Darkolos

    Darkolos

    Joined:
    Jan 7, 2021
    Posts:
    2
    So I wanted to make a Top-Down type shooter. For that I need the character to follow the mouse and also lock the mouse in the screen (like if you would play a 3d Shooter, I dont want any limit of how far you can go with your mouse and also not go offscreen)
    But the Character just keeps jumping around while I move my mouse.
    I think I know what the problem is, Im just not experienced enough to find a solution myself.
    For the mouse locking I simply used:

    Screen.lockCursor = true;

    This is my method to detect the mouse movement:

    void CheckRotation()
    {
    var dir = Input.mousePosition - Camera.main.WorldToScreenPoint(transform.position);
    var angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
    Player.transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
    }
     
  2. Chris-Trueman

    Chris-Trueman

    Joined:
    Oct 10, 2014
    Posts:
    974
    Use Cursor.lockState = CursorLockMode.Confined; to confine the mouse to the game screen. Screen.lockCursor is marked as obsolete so I wouldn't use it. When you use Screen.lockCursor = true, Input.mousePosition should be the center of the screen as that will lock it to the center, so it's probably giving you small values for the direction causing it to jump all over the place.
     
  3. Darkolos

    Darkolos

    Joined:
    Jan 7, 2021
    Posts:
    2
    Thank you for you help!
    But now I have the problem that I hit the border of the screen if I go too far out which really limits the players movement. Is there an easy fix for that too?
     
  4. Chris-Trueman

    Chris-Trueman

    Joined:
    Oct 10, 2014
    Posts:
    974
    No easy fix. You would need to create a virtual mouse or aimer and restrict how far you can move the mouse/aimer.

    For me what you want to fix is a non-issue. Change the mouse cursor to an aimer texture with the hotspot set to the center. If the user moves too far away and looses some control, too bad so sad suck it up buttercup. Terraria doesn't do anything about it, not too many top down games do anything about. That's what I recommend, don't worry about it.
     
unityunity