Hello Im new to Unity this code is from a youtube tutorial I follow the instructions correctly but my Enemy does not flipping even in the Idle State. What I want is, I want the enemy face the Main Character for example the player comes from the rightside and the enemy is facing left I want the enemy face the rightside. Just like he’s facing the player and the AI movement is good when I enter the trigger the enemy chasing the player but he doesn’t flip. (Sorry for my bad english)
By the way this is my code from the tutorial.
public float EnemySpeed;
Animator EnemyAnimator;
public GameObject EnemyGraphic;
bool canFlip = true;
bool facingRight = false;
float flipTime = 5f;
float FlipChance = 0f;
//attacking
public float attackTime;
float StartAttackTime;
bool attacking;
Rigidbody2D EnemyRB;
void Start ()
{
EnemyAnimator = GetComponentInChildren<Animator>();
EnemyRB = GetComponent<Rigidbody2D>();
}
void Update ()
{
if(Time.time > FlipChance)
{
if (Random.Range(0, 10) >= 5)
{
flipFacing();
FlipChance = Time.time + flipTime;
}
}
}
void flipFacing()
{
if(!canFlip) return;
float FacingX = EnemyGraphic.transform.localScale.x;
FacingX -= 1f;
EnemyGraphic.transform.localScale = new Vector3(FacingX, EnemyGraphic.transform.localScale.y, EnemyGraphic.transform.localScale.z);
facingRight = !facingRight;
}
void OnTriggerEnter2D(Collider2D col)
{
if (col.tag == "Player")
{
if (facingRight && col.transform.position.x < transform.position.x) flipFacing();
else if (!facingRight && col.transform.position.x > transform.position.x) flipFacing();
}
canFlip = false;
attacking = true;
StartAttackTime = Time.time + attackTime;
}
void OnTriggerStay2D(Collider2D col)
{
if(col.tag == "Player")
{
if(attackTime < Time.time)
{
if (!facingRight) EnemyRB.AddForce(new Vector2(-1, 0) * EnemySpeed);
else EnemyRB.AddForce(new Vector2(1, 0) * EnemySpeed);
EnemyAnimator.SetBool("Running", attacking);
}
}
}
void OnTriggerExit2D(Collider2D col)
{
if(col.tag == "Player")
{
canFlip = true;
attacking = false;
EnemyRB.velocity = new Vector2(0f,0f);
EnemyAnimator.SetBool("Running", attacking);
}
}
}