Search Unity

Help: Aiming Towards Mouse Direction

Discussion in '2D' started by unity_mtDktG8qaAuefQ, Apr 10, 2019.

  1. unity_mtDktG8qaAuefQ

    unity_mtDktG8qaAuefQ

    Joined:
    Apr 10, 2019
    Posts:
    2
    Hi everyone, i'm a total beginner at Unity even if i started learning c# a year ago, so i'm for sure a better coder then an "artist", but i'm having troubles with aiming towards mouse position in a top-down-shooter.
    Every kind of help is much appreciated, and sorry for my english, not a native speaker here.

    So:
    I have an Empty Game Object wich is my Player, with 5 childs that are his body parts, i actually have: head, left arm, right arm, torso, and weapon
    Here's what it look like:
    (It's a free asset from the unity store, i imported every single piece from the PSD)
    unityask.png
    So far so good (I think).
    My "Player" object has this script:
    Code (CSharp):
    1. void Update()
    2.     {
    3.         MouseAim();
    4.     }
    5.  
    6.  
    7.     void MouseAim()
    8.     {
    9.         Vector3 dir = Input.mousePosition - Camera.main.WorldToScreenPoint(transform.position);
    10.         float angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
    11.         transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
    12.     }
    13. }
    So, the player is actually rotating on itself and it's working fine, but the problem is that the "Mouse position" start from his right shoulder, instead of his weapon
    This is the result, the white line is where my cursor is pointing.
    unityhelp2.png
    If i rotate my cursors, the player will actually rotate, but he will aim with is shoulder:
    unityhelp3.png

    What i'm doing wrong? i would like to aim starting from the weapon in the direction of the mouse, not with his shoulder.
    Thank you in advance and have a nice day everyone :)


    EDIT: I actually fixed it by giving all the piecese -90 on their Z axis, so the player starting facing right instead than top, don't know if it's the right thing to do tho.
     
    Last edited: Apr 10, 2019