Search Unity

Rotate Player to face mouse position

Discussion in 'Scripting' started by PenDigi, Nov 10, 2015.

  1. PenDigi

    PenDigi

    Joined:
    Sep 19, 2015
    Posts:
    14
    Hi all, please see the following code snippet


    Vector3 mv = Input.mousePosition;
    mv.z = 10;
    mv = Camera.main.ScreenToWorldPoint (mv);
    mv = mv - transform.position;

    float mouseToAxis = Vector3.Angle (mv, new Vector3 (1, 0, 0));
    float bodyToAxis = Vector3.Angle (transform.right, new Vector3 (1, 0, 0));

    float angle = mouseToAxis - bodyToAxis;
    angle = Mathf.Clamp (angle, -move.rotation_speed, move.rotation_speed);

    transform.Rotate (new Vector3 (0, 0, angle));


    The above code is used to rotate my player object to face the mouse position.
    It works only as long as my mouse is within the positive X quadrants relative to the player's local space.
    E.g. the mouse must be above the imaginary horizontal line which intersects with my player object.

    After much investigation I realised that mouseToAxis provides the angle between the Position Vector of the Mouse to the X-Axis, both the positive and negative Y-Axis gives a result of 90 degrees. However I want the negative Y-axis to give a bearing of 180+90 instead of just 90.

    Does anyone know how I could accomplish this either mathematically or through some Unity interface? Thanks in advance!
     
  2. PenDigi

    PenDigi

    Joined:
    Sep 19, 2015
    Posts:
    14
    Okay I feel kinda dumb for posting this.

    Here is a hackish fix


    if (mv.y < 0)
    mouseToAxis = 360 - mouseToAxis;

    This will correct the angle into a bearing and generates the correct results that I needed.
     
  3. PenDigi

    PenDigi

    Joined:
    Sep 19, 2015
    Posts:
    14
    For anyone who is interested in the full implementation here it is:


    Vector3 mv = Input.mousePosition;
    mv.z = 10;
    mv = Camera.main.ScreenToWorldPoint (mv);
    mv = mv - transform.position;

    float mouseToAxis = Vector3.Angle (mv, new Vector3 (1, 0, 0));
    if (mv.y < 0)
    mouseToAxis = 360 - mouseToAxis;

    float bodyToAxis = Vector3.Angle (transform.right, new Vector3 (1, 0, 0));
    if (transform.right.y < 0)
    bodyToAxis = 360 - bodyToAxis;

    float angle = mouseToAxis - bodyToAxis;
    if (angle > 180)
    angle = -(360 - angle);
    else if (angle < -180)
    angle = 360 + angle;

    angle = Mathf.Clamp (angle, -move.rotation_speed, move.rotation_speed);
    transform.Rotate (new Vector3 (0, 0, angle));


    This simply makes the player object rotate slowly towards the mouse position. Some parts might be a little unnecessary so anyone who knows his vector math can probably optimize this quite a bit.

    Thanks.
     
    Last edited: Nov 10, 2015