- Home /
How to C# script a 2d top-down NPC's Animation
So I made a Player and a Non Player Character. I wrote a script so the NPC will find the shortest path and follow the Player from a certain distance. It will also stop when the NPC touches the Player. Based on my NPC script, how do I input the animation when the NPC is moving along the X and Y axis. I only have Top,Down,Left,Right animations for the NPC.
Here is my NPC AI script
using UnityEngine;
using System.Collections;
public class followingAI : MonoBehaviour
{
Transform target;
public float speed;
private float minDistance = 1;
private float maxDistance = 5;
private float range;
void Update ()
{
target = GameObject.FindGameObjectWithTag ("Player").transform;
range = Vector2.Distance(transform.position, target.position);
if (range <= maxDistance)
{
transform.position = Vector2.MoveTowards(transform.position, target.position, speed * Time.deltaTime);
}
if (range <= minDistance)
{
speed = 0;
Destroy (gameObject, 5);
}
}
}
Also here is my first attempt but it failed terribly :(
using UnityEngine;
using System.Collections;
public class enemyMovements : MonoBehaviour
{
private Animator _animator;
private Rigidbody2D _rigidbody2D;
void start ()
{
_animator = GetComponent <Animator> ();
_rigidbody2D = GetComponent <Rigidbody2D> ();
}
void update ()
{
CheckDirection ();
}
void CheckDirection ()
{
float dirX = _animator.GetFloat ("eVelX");
float dirY = _animator.GetFloat ("eVelY");
if (dirX * rigidbody2D.velocity.x <= 0 )
{
WalkAnimation (-1, 0);
}
else if (dirX * rigidbody2D.velocity.x >= 0 )
{
WalkAnimation (1, 0);
}
else if (dirY * rigidbody2D.velocity.y >= 0 )
{
WalkAnimation (0, 1);
}
else (dirY * rigidbody2D.velocity.y <= 0 )
{
WalkAnimation (0, -1);
}
}
void FixedUpdate ()
{
Move ();
}
void Move ()
{
float dirX = _animator.GetFloat ("eVelX");
float dirY = _animator.GetFloat ("eVelY");
}
void WalkAnimation (float x, float y)
{
_animator.SetFloat ("eVelX", x);
_animator.SetFloat ("eVelY", y);
}
}
Yes. I'm kinda also having that problem.. Years later, did you got the solution to this?
Your answer
Follow this Question
Related Questions
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
2D Sprite constantly flipping 0 Answers
How to change animation's speed in C#? 2 Answers
Trying to change character model on mouse down 1 Answer
How can I disable a Method. 1 Answer