2D Rotate to Mouse twitching while moving

Hello,

I’m trying to make a basic 2D top down player controller, but I’m having an issue with my Rotate() method, it’s supposed to make the player rotate to look at the mouse.
Rotate() works fine when player is idle, but when I start moving while moving around my cursor Rotate() becomes inaccurate.
7pydb

using UnityEngine;

public class PlayerController : MonoBehaviour
{
    private Vector3 _mousePosition;
    private Vector2 _movement;

    private Rigidbody2D _rb2D;
    private Camera _camera;

    [Header("Speed")]
    public float walkSpeed = 5.0f;

   
    private void Start()
    {
        _camera = Camera.main;
        _rb2D = GetComponent<Rigidbody2D>();
    }
   
    private void Update()
    {
        HandleInput();
        if (Time.frameCount % 2 == 0) Rotate();
    }

    private void FixedUpdate()
    {
        Move(_movement);
    }

    private void Rotate()
    {
        var dir = Input.mousePosition - _camera.WorldToScreenPoint(transform.position);
        var angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
        _rb2D.MoveRotation(Quaternion.AngleAxis(angle, Vector3.forward));
    }

    private void HandleInput()
    {
        _movement = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
    }

    private void Move(Vector2 direction)
    {
        direction = direction.normalized;
        _rb2D.MovePosition((Vector2) transform.position + walkSpeed * Time.fixedDeltaTime * direction);
    }
}

Thanks for reading :slight_smile:

I don’t see anything obviously wrong.

The only thing I can think of is that the camera isn’t set to Orthographic so you’re getting wrong values from _camera.WorldToScreenPoint.

Feel free to upload it here and I can take a quick look.

A few side notes:

  • MoveRotation takes an angle so you can just pass the angle. Quaternion is supported but it’s converted to a Z-axis angle anyway.
  • Using Transform.position will be invalid if you’re using interpolation as that’ll just be the interpolated position and not the current position of the Rigidbody2D. Use Rigidbody2D.position as the bases. It’ll also be Vector2.
1 Like

Thanks for the suggestions, I tried to implement them and I also uploaded my file :slight_smile:

I fixed my issue by moving Rotate() to LateUpdate() instead of Update() but I’m still not 100% sure why it worked. I tried to debug and it seemed like the offset from the mouse position to the player changed a little while moving the player without moving the mouse cursor.

EDIT: I uploaded the script instead of the project, I’m dumb haha. The .zip should be uploaded now.

I could already see your file above so uploading it won’t help. I was trying to suggest uploading your project as it seems something else is going wrong.

I uploaded the project as Robber2D.zip.

So I just tried your project and it seems to work fine so it’s very strange indeed that you’re seeing an issue.