Search Unity

  1. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

2d sprite look at mouse

Discussion in '2D' started by ChaosD, Nov 17, 2013.

  1. ChaosD

    ChaosD

    Joined:
    Feb 15, 2013
    Posts:
    4
    Hello,
    i´ve been looking around for quite some time now and all i found were scripts that worked odd for me. I have a top down scene where my player (sprite) moves around. I want him alwys to face the mouse coursor. I tried several scripts from around the forums but most of them rotated my sprite in a way that it either got invisible (90 degree to the camera) or, as my last attempt, facing down slowly, the father away the mouse moves.
    This is my current script:
    Code (csharp):
    1.    
    2. void Update () {
    3.         mousePosition = Input.mousePosition;           
    4.         mousePosition = Camera.main.ScreenToWorldPoint(mousePosition);
    5.         //transform.LookAt(new Vector3(mousePosition.x, mousePosition.y, transform.position.x));
    6.         Quaternion rot = Quaternion.LookRotation( transform.position - mousePosition, Vector3.forward );
    7.         transform.rotation = rot;  
    8.     }
    9.  
    Are there any 2d specific helpers/classes designed for this or do i really need to go down the 3d road here?

    Thanks in advance!
     
    w-p likes this.
  2. ChaosD

    ChaosD

    Joined:
    Feb 15, 2013
    Posts:
    4
    Found a solution by myself - if anyone has the same problem, this is what iam using now:

    Code (csharp):
    1. void Update () {
    2.         mousePosition = Input.mousePosition;           
    3.         mousePosition = Camera.main.ScreenToWorldPoint(mousePosition);
    4.  
    5.         //transform.LookAt(new Vector3(mousePosition.x, mousePosition.y, transform.position.x));
    6.         Quaternion rot = Quaternion.LookRotation(transform.position - mousePosition, Vector3.forward );
    7.         transform.rotation = rot;  
    8.         transform.eulerAngles = new Vector3(0, 0,transform.eulerAngles.z);
    9.     }
    The whole Quaternion and Angle stuff is really confusing to me.

    Is this the right way for 2d?
     
    WinterboltGames and w-p like this.
  3. PJRM

    PJRM

    Joined:
    Mar 4, 2013
    Posts:
    303
    I have the same problem!
    It should be an overload method of LookRotation for 2D purposes, like the script reference:
    Code (csharp):
    1.  
    2. static Quaternion LookRotation(Vector2 forward, Vector2 upwards = Vector2.up); // For 2D projects
    3.  
    Some methods and classes works with 3D only, not 2D.
    So far my 2D spaceRocks is going well, but to make the enemies face the player... is a hell.
    Thanks for the solution!