Hey guys, I am working on a 2D platformer and I was having trouble with my enemy ai. When the enemy reaches a wall or cliff it’s supposed to turn around but it currently just flips back and forth
public class EnemyPatrol : MonoBehaviour
{
public LayerMask groundLayer;
public float speed;
public bool movingRight = true;
public bool onGround, hitWall;
public Transform groundDetection;
void Update()
{
Patrol();
}
void Patrol()
{
onGround = Physics2D.Raycast(groundDetection.position, Vector2.down, 0.1f, groundLayer);
hitWall = (Physics2D.Raycast(transform.position, Vector2.left, 0.75f, groundLayer) || Physics2D.Raycast(transform.position, Vector2.right, 0.75f, groundLayer));
if (!movingRight)
{
transform.Translate(Vector2.left * speed * Time.deltaTime);
ChangeDirection(-0.2f);
}
else
{
transform.Translate(Vector2.right * speed * Time.deltaTime);
ChangeDirection(0.2f);
}
if (!onGround || hitWall)
{
if (movingRight)
{
movingRight = false;
}
else
{
movingRight = true;
}
}
}
void ChangeDirection(float direction)
{
Vector3 tempScale = transform.localScale;
tempScale.x = direction;
transform.localScale = tempScale;
}
}