Search code examples
c#unity-game-enginerotation2d-gameseuler-angles

Mouse look turns right side towards mouse pointer


Im trying to get my GameObject to point towards the mouse. It has a child object with a sprite. The childs rotation is set to 0 on all zxis. The sprite points upwards (positive X) at start. The GameObject rotates with the mouse pointer but its always turning its right side towards the mouse pointer. Also when i add force forward it accelerates at the same direction the sprite is pointing which as stated before is not the direction the mouse is. What is my code missing?

  var cam = Camera.main;

    // Distance from camera to object.  We need this to get the proper calculation.
    float camDistance = cam.transform.position.y - transform.position.y;

    // Get the mouse position in world space. Using camDis for the Z axis.
    Vector3 mouse = cam.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, camDistance));

    float AngleRad = Mathf.Atan2(mouse.y - transform.position.y, mouse.x - transform.position.x);
    float angle = (180 / Mathf.PI) * AngleRad;

    rb2d.rotation = angle;

Solution

  • Your shape is rotated by 90 degrees due to the way that your calculations resolve the angle, you can account for this by using:

    rb2.rotation = angle - 90;