Whenever my change direction function is called unity crashes. I’m pretty sure it has to do with the while loop but I don’t know why.
I’m trying to make the enemy follows the player, but right now whenever the player changes direction the enemy changes direction instantly. I want to make it so that the enemy gradually changes direction.
public class EnemyAI : MonoBehaviour
{
private Animator anim;
private LimbController limbs;
private GameObject player;
public float speed;
private int playerDir;
private int lastPlayerDir;
private float dir;
private void Awake()
{
limbs = GetComponent<LimbController>();
player = GameObject.FindGameObjectWithTag("Player");
anim = GetComponent<Animator>();
}
private void Start()
{
playerDir = player.transform.position.x > transform.position.x ? 1 : -1;
lastPlayerDir = playerDir;
dir = playerDir;
}
private void Update()
{
playerDir = player.transform.position.x > transform.position.x ? 1 : -1;
if(lastPlayerDir != playerDir)
{
ChangeDirection(playerDir);
}
if(player.transform.position.x - transform.position.x > 5 || player.transform.position.x - transform.position.x < -5)
{
limbs.body.bone.velocity = new Vector2(dir * speed, limbs.body.bone.velocity.y);
anim.SetBool("isWalking", true);
}
else
anim.SetBool("isWalking", false);
}
private void ChangeDirection(int changeDir)
{
while(dir != playerDir)
{
dir += changeDir * Time.deltaTime;
}
lastPlayerDir = playerDir;
}
}