Instead of implementing like Rick did, I did it a bit differently.
I do the scale according to the moveSpeed of the enemy, and since we use Mathf.Sign (-1 to 1), if the enemy is moving to the right, it’ll always be 1 and to the left always -1. And since we want to be able to create enemies facing whatever side programatically, I also flip the sprite as soon as the enemy is created.
Also added some other stuff for changing the enemy behaviour a little bit.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyMovement : MonoBehaviour
{
[Header("Enemy Configuration")]
[SerializeField] float moveSpeed;
// Cached Reference
Rigidbody2D enemyRigidbody;
Animator animator;
void Start()
{
animator = GetComponent<Animator>();
enemyRigidbody = GetComponent<Rigidbody2D>();
FlipSprite();
}
// Update is called once per frame
void Update()
{
Move();
}
private void Move()
{
animator.SetBool("isWalking", true);
enemyRigidbody.velocity = new Vector2(moveSpeed, 0f);
}
private void OnTriggerExit2D(Collider2D otherCollider)
{
moveSpeed *= -1;
FlipSprite();
}
private void FlipSprite()
{
transform.localScale = new Vector2(Mathf.Sign(moveSpeed), 1f);
}
}