Trying to make that the head looking towards the mouse but something went wrong

Hi! I’m trying to make that the head looking towards the mouse, but for some reason, it works so weirdly. It only works in the bottom left corner. Is it missing something or I did something wrong?

Video about it:

peskycolorfulblacknorwegianelkhound

Here’s the code:

public class PlayerMovementt : MonoBehaviour
{
    public float moveSpeed = 5f;

    public Rigidbody2D rb;
    public Camera cam;

    Vector2 movement;
    Vector2 mousePos;

    void Update()
    {
        movement.x = Input.GetAxisRaw("Horizontal");
        movement.y = Input.GetAxisRaw("Vertical");

        mousePos = cam.WorldToScreenPoint(Input.mousePosition);
    }

    void FixedUpdate()
    {
        rb.MovePosition(rb.position + movement * moveSpeed);

        Vector2 lookDir = mousePos - rb.position;
        float angle = Mathf.Atan2(lookDir.y, lookDir.x) * Mathf.Rad2Deg - 90f;
        rb.rotation = angle;
    }
}

I’m made it from this video:

You should be using Camera.ScreenToWorldPoint, not Camera.WorldToScreenPoint.

If I change it to that, then it stops rotating

Make sure that your camera has a rotation of (0, 0, 0) and that projection mode is set to Orthographic.

1 Like

Thank you so much! :slight_smile: It fixed it.

1 Like