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

Problem controlling NPC animation transitions 2D using X values

Discussion in '2D' started by tubuenvecinospiderman, Aug 1, 2019.

  1. tubuenvecinospiderman

    tubuenvecinospiderman

    Joined:
    Aug 1, 2019
    Posts:
    1
    Hello, I am working on 2D NPC animation and transitions, and I want to switch between Walking Left, Idle and Walking Right animations according to NPC's movement in X values. I've found Brackeys' on Pathfinding using A*Pathfinding tool, so I tried to make this using the code on the video, but It just flips the NPC sprite. I managed to switch transitions but only when the value of target is >=0 (Animation changes between Idle and Walk Right, but not Left) Is there another way to do this? I've been working on this for weeks now, and I cannot find any solution. This is my attempt to achieve this:

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using Pathfinding;
    5. public class EnemyGFX : MonoBehaviour
    6. {
    7.     public AIPath aiPath;
    8.     public Animator animator;
    9.     //My edit
    10.     string animationState = "AnimationState";
    11.     enum CharStates
    12.     {
    13.         DogIdleLeft =1,
    14.         DogWalkLeft =2,
    15.         DogWalkRight =3,
    16.     }
    17.     //My edit
    18.     private void Start()
    19.     {
    20.         animator = GetComponent<Animator>();
    21.     }
    22.     // Update is called once per frame
    23.     void Update()
    24.     {
    25.         if (aiPath.desiredVelocity.x >= 0.01f)
    26.         {
    27.             transform.localScale = new Vector3(-1f, 1f, 1f);
    28.         } else if (aiPath.desiredVelocity.x <= -0.01f)
    29.         {
    30.             transform.localScale = new Vector3(1f, 1f, 1f);
    31.         }
    32. // My edit
    33.         if(aiPath.desiredVelocity.x > 0)
    34.         {
    35.             animator.SetInteger(animationState,(int)CharStates.DogWalkLeft);
    36.         }
    37.         else if (aiPath.desiredVelocity.x < 0)
    38.         {
    39.             animator.SetInteger(animationState, (int)CharStates.DogWalkRight);
    40.         }
    41.         else  
    42.         {
    43.             animator.SetInteger(animationState, (int)CharStates.DogIdleLeft);
    44.         }
    45.         }
    46.        
    47. //My edit      

    and this is Brackeys video:


    Is there another way to do this effect?
    Thanks in advance!