Search Unity

2D Mouse Aiming

Discussion in '2D' started by jvt619, Nov 26, 2013.

  1. jvt619

    jvt619

    Joined:
    Jul 4, 2013
    Posts:
    53
    How can I achieve mouse aiming in unity?
     
  2. TomasJ

    TomasJ

    Joined:
    Sep 26, 2010
    Posts:
    256
    You can find the angle between your mouse position and character:
    Code (csharp):
    1.  
    2. public static float SignedAngle(Vector2 a, Vector2 b)
    3. {
    4. Vector3 a3 = (Vector3)a;
    5. Vector3 b3 = (Vector3)b;
    6. var angle = Vector3.Angle(a3, b3);
    7. return angle * Mathf.Sign(Vector3.Cross(a3, b3).z);
    8. }
    9.  
    and then rotate your GO around the Z axis like so:
    Code (csharp):
    1.  
    2. float angle = SignedAngle(dir, new Vector3(0,1));
    3. Quaternion lookDir = Quaternion.AngleAxis(angle, new Vector3(0,0,-1));
    4. transform.localRotation = lookDir;
    5.