Search Unity

Idle animation mouse rotation

Discussion in 'Animation' started by Moomit, Apr 9, 2021.

  1. Moomit

    Moomit

    Joined:
    May 2, 2020
    Posts:
    4
    So I have my player character with his animations set up, if he goes left it plays the animations if he stops it plays the left idle animations. What I also want to do, to change player idle animations by the mouse position. So basically if he is idle and you would move the mouse around him the sprites would change depending on the direction of the mouse. Unfortunately, I have no idea how to do this. So far I have made this but i get errors

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class PlayerMovement : MonoBehaviour
    6. {
    7.     public float moveSpeed = 2f;
    8.     public Rigidbody2D rb;
    9.     Animator thisAnim;
    10.     float lastX, lastY;
    11.  
    12.     void Start()
    13.     {
    14.         thisAnim = GetComponent<Animator>();
    15.     }
    16.  
    17.     // Update is called once per frame
    18.     void Update()
    19.     {
    20.         Move();
    21.     }
    22.  
    23.     void Move()
    24.     {
    25.         Vector3 rightMovement = Vector3.right * moveSpeed * Time.deltaTime * Input.GetAxis("Horizontal");
    26.         Vector3 upMovement = Vector3.up * moveSpeed * Time.deltaTime * Input.GetAxis("Vertical");
    27.  
    28.         Vector3 heading = Vector3.Normalize(rightMovement + upMovement);
    29.  
    30.         transform.position += rightMovement;
    31.         transform.position += upMovement;
    32.  
    33.         UpdateAnimation(heading);
    34.     }
    35.  
    36.     void UpdateAnimation(Vector3 dir)
    37.     {
    38.  
    39.         if (dir.x == 0f && dir.y == 0f)
    40.         {
    41.             Vector3 mouseLocationPixels = new Vector3(Input.mousePosition.x, Input.mousePosition.y);
    42.  
    43.             Vector3 mouseLocationWorld = Camera.main.ScreenToWorldPoint(mouseLocationPixels);
    44.             lookDirection = (mouseLocationWorld - transform.position).normalized;
    45.  
    46.             thisAnim.SetFloat("LastHorizontal", lookDirection);
    47.             thisAnim.SetFloat("LastVertical", lookDirection);
    48.             thisAnim.SetBool("Moving", false);
    49.         }
    50.         else
    51.         {
    52.             lastX = dir.x;
    53.             lastY = dir.y;
    54.             thisAnim.SetBool("Moving", true);
    55.         }
    56.         thisAnim.SetFloat("Horizontal", dir.x);
    57.         thisAnim.SetFloat("Vertical", dir.y);
    58.     }
    59.  
    60. }