I’m working on an enemy AI in unity 2d and I would like to make it always look at the player only on one axis (x-axis) and in a certain range.
My current code is:
void Chase()
{
t = this.transform;
if (Vector3.Distance(t.position, target.position) < detectDistance)
{
Vector3 vectorToTarget = target.position - transform.position;
float moveDistance = moveSpeed * Time.deltaTime;
if (vectorToTarget.magnitude > moveDistance)
{
transform.position = Vector2.MoveTowards(transform.position, new Vector2(target.position.x, transform.position.y), moveSpeed * Time.deltaTime);
}
else
{
transform.position = target.position;
}
if (target.position.x > transform.position.x && !facingRight)
Flip();
if (target.position.x < transform.position.x && facingRight)
Flip();
chasing = true;
animation.SetBool("walking", false);
animation.SetBool("running", true);
animation.SetBool("idle", false);
}
else
{
chasing = false;
animation.SetBool("walking", false);
animation.SetBool("running", false);
animation.SetBool("idle", true);
}
}
I think that the could would go in the Flip function which is currently empty but I’m not sure.