Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

How to get player to face the last direction they moved towards? (2D Game)

Discussion in '2D' started by Tarik1989, Oct 8, 2019.

  1. Tarik1989

    Tarik1989

    Joined:
    Oct 6, 2019
    Posts:
    4
    Hi All,

    Appreciate any help on this challenge. So I've created my player movement script, blend tree animations; all working well. I am now trying to implement code so if the player was moving left for example, when I stop he stays in the left facing sprite animation. Currently when I stop the player snaps back to his default animation which is facing down. Any guidance on what needs to be altered below? I have tried Quaternion.LookRotation however this seems to work for 3D and not 2D movement.

    Code (CSharp):
    1.     private void PlayerMovement()
    2.     {
    3.         if (canMove && knockBackCount <= 0)
    4.         {
    5.  
    6.             movement.x = CrossPlatformInputManager.GetAxisRaw("Horizontal") * Time.fixedDeltaTime;
    7.             movement.y = CrossPlatformInputManager.GetAxisRaw("Vertical") * Time.fixedDeltaTime;
    8.  
    9.             movement.Normalize();
    10.  
    11.             body.velocity = movement * speed;
    12.  
    13.             Dash();
    14.  
    15.         }
    16.  
    17.         else
    18.         {
    19.             KnockBack();
    20.         }
    21.     }
    22.  
    23.  
    24.  
    25.     private void PlayerAnimation()
    26.     {
    27.        
    28.         if(Mathf.Approximately(movement.x, 0) && Mathf.Approximately(movement.y, 0))
    29.         {
    30.             animator.SetBool("isWalking", false);
    31.  
    32.  
    33.  
    34.         }
    35.  
    36.  
    37.         else
    38.         {
    39.             animator.SetBool("isWalking", true);
    40.  
    41.         }
    42.  
    43.  
    44.         animator.SetFloat("xDir", movement.x);
    45.         animator.SetFloat("yDir", movement.y);
    46.     }