I am making a 2d platformer, and i am trying to add enemies. i am trying to make the enemy move back and forth on a platform, flipping its direction when it gets to the edge or a wall. i am using empty objects and unity’s overlap circle feature to detect if the enemy is close to a wall or edge. however, the enemy is constantly flipping back and forth. Am i doing something wrong, and if so how do i fix it? here is the enemy pathfinding code:
private void EnemyMove()
{
if (!IsGrounded() || IsWalled())
{
Flip();
}
else
{
rb.velocity = new Vector2(horizontal * speed, rb.velocity.y);
}
}
public bool IsGrounded()
{
return Physics2D.OverlapCircle(groundCheck.position, 0.2f, groundLayer);
}
public bool IsWalled()
{
return Physics2D.OverlapCircle(wallCheck.position, 0.2f, groundLayer);
}
private void Flip()
{
Vector3 localScale = transform.localScale;
localScale.x *= -1f;
transform.localScale = localScale;
horizontal = horizontal * -1;
}