- Home /
Question by
AnibalRetro · Nov 24, 2021 at 11:44 AM ·
animationunity 2dcontrollernpc
How can I make the animation match when the NPC walks left or right?
I have some NPCs that randomly walk within a range, however when I can't determine when they are walking left or right so the animation looks wrong.
How can I make the animation match when the NPC walks left or right?
Here is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NPCController : MonoBehaviour
{
private float waitTime;
private Animator _animator;
private SpriteRenderer _renderer;
public Transform moveSpot;
private bool _facingRight = true;
public float lastXVal;
public float speed;
public float startWaitTime;
public float minX;
public float maxX;
public float minY;
public float maxY;
void Awake()
{
_animator = GetComponent<Animator>();
_renderer = GetComponent<SpriteRenderer>();
}
void Start()
{
waitTime = startWaitTime;
moveSpot.position = new Vector2(Random.Range(minX, maxX), Random.Range(minY, maxY));
}
void Update()
{
transform.position = Vector2.MoveTowards(transform.position, moveSpot.position, speed * Time.deltaTime);
if (Vector2.Distance(transform.position, moveSpot.position) < 0.2f)
{
if (transform.hasChanged)
{
if (transform.position.x < lastXVal)
{
transform.eulerAngles = new Vector3(0, -180, 0);
//Update lastXVal
lastXVal = transform.position.x;
Debug.Log("Decreased!");
}
else if (transform.position.x > lastXVal)
{
transform.eulerAngles = new Vector3(0, 0, 0);
//Update lastXVal
lastXVal = transform.position.x;
Debug.Log("Increased");
}
transform.hasChanged = false;
}
//Change animation state
if (waitTime <= 0)
{
_animator.SetBool("Walk", true);
moveSpot.position = new Vector2(Random.Range(minX, maxX), Random.Range(minY, maxY));
waitTime = startWaitTime;
}
else
{
_animator.SetBool("Walk", false);
_animator.SetBool("Idle", true);
waitTime -= Time.deltaTime;
}
}
}
public void Decrease()
{
if (transform.hasChanged)
{
if (transform.position.x < lastXVal)
{
//Update lastXVal
lastXVal = transform.position.x;
Debug.Log("Decreased!");
}
else if (transform.position.x > lastXVal)
{
//Update lastXVal
lastXVal = transform.position.x;
Debug.Log("Increased");
}
transform.hasChanged = false;
}
}
}
Comment
Your answer
![](https://koobas.hobune.stream/wayback/20220613045710im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Character moving up when animated. 1 Answer
Not Run while Aiming; Slope Terrain Making Object Faster 0 Answers
2 characters in 1 humanoid? 1 Answer
Need help with tool animations!! 1 Answer