2D How to get enemy to face the player while moving
So this is for a top-down action RPG kind of like Zelda, and I've got 4 separate animations for the enemy to face depending on which direction they're moving. I'm trying to get the enemy to follow the player if they're within range, which works, but there's a bit of a delay for the enemy to face the player, and sometimes it'll face a different direction while chasing the player, which looks pretty strange. Any ideas on how to fix this?
testController.cs
public class testController : MonoBehaviour {
public Transform Player;
public float ChaseSpeed = 2f;
public float Range = 4f;
private float CurrentSpeed;
private float attackTimer;
private float attackCooldown = 0.5f;
private bool canAttack;
private Animator anim;
void Start() {
anim = GetComponent<Animator>();
}
void Update() {
if (Vector3.Distance(transform.position, Player.position) <= Range)
{
if (Vector3.Distance(transform.position, Player.position) <= 1f)
{
anim.SetBool("isWalking", false);
CurrentSpeed = 0f;
Attack ();
}
else
{
anim.SetBool("isWalking", true);
anim.SetFloat("input_x", Player.localPosition.x);
anim.SetFloat("input_y", Player.localPosition.y);
CurrentSpeed = ChaseSpeed * Time.deltaTime;
transform.position = Vector2.MoveTowards(transform.position, Player.position, CurrentSpeed);
}
}
else
{
anim.SetBool("isWalking", false);
CurrentSpeed = 0f;
}
}
Comment
Your answer
Follow this Question
Related Questions
Move enemy towards player if enemy is in Camera bounds? 1 Answer
Enemies cannot kill Player. 0 Answers
Character continues moving when locked onto an enemy 1 Answer
Enemy Chasing player? 0 Answers
Enemy AI script for 2D platformer 1 Answer