Question by
creepermold9 · Jul 25, 2019 at 09:53 PM ·
unity 2d
How do you make a character flip in Unity 2d
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.
Comment
Answer by goutham12 · Jul 26, 2019 at 06:58 AM
voi FIip(){
Vector3 scale = transform.localScale;
scale.x = -scale.x;
transform.localScale = scale;
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612205406im_/https://answers.unity.com/themes/thub/images/avi.jpg)