Here’s my code in case it helps anyone
public class EnemyMovement : MonoBehaviour
{
[SerializeField] private float moveSpeed = 2f;
[SerializeField] private Vector2 direction;
private Rigidbody2D rb;
private RaycastHit2D raycastHit;
private LayerMask groundLayer;
private void Awake()
{
rb = GetComponent<Rigidbody2D>();
}
private void Start()
{
groundLayer = LayerMask.GetMask("Ground");
direction = Vector2.right;
}
private void Update()
{
rb.velocity = direction * moveSpeed;
raycastHit = Physics2D.Raycast(transform.position, direction, .5f, groundLayer);
Debug.DrawRay(transform.position, direction * .5f, Color.red);
if(raycastHit.collider != null)
{
ChangeDirection(-direction);
FlipEnemy();
}
}
private void ChangeDirection(Vector2 newDirection)
{
direction = newDirection;
}
private void FlipEnemy()
{
transform.localScale = new Vector2(direction.x, transform.localScale.y);
}
}