How to read the movment speed of sprite and flip basied upon it

I am trying to get an enemy to follow the player when he get’s to close, but I need him to flip between left and right but my only problem is I don’t know how to monitor the speed of the enemy so I don’t know when to tell it to flip, can someone please help me? here is my code: I do have a rigidbody2D attached to it so you can also use that.

public class FlyingEnemy : MonoBehaviour
{

``````private PlayerController player;

public float moveSpeed;

public float playerRange;

public GameObject deathAffect;

public int pointsOnDeath;

public LayerMask playerLayer;

private bool playerInRange;

private Rigidbody2D RB;

// Use this for initialization
void Start ()
{
player = FindObjectOfType<PlayerController>();

RB = FindObjectOfType<Rigidbody2D>();
}

// Update is called once per frame
void Update ()
{
playerInRange = Physics2D.OverlapCircle(transform.position, playerRange, playerLayer);

if (playerInRange)
{
transform.position = Vector3.MoveTowards(transform.position, player.transform.position, moveSpeed * Time.deltaTime);
}

if (RB.velocity.magnitude < 0)
{
transform.localScale = new Vector3(1f, 1f, 1f);
Debug.Log("moving left");
}

if(RB.velocity.magnitude > 0)
{
transform.localScale = new Vector3(-1f, 1f, 1f);
Debug.Log("moving right");
}
``````

}

RB.velocity.magnitude will always return a positive number so you cannot use that to check the direction of travel instead just check the x component of the velocity.

``````if(RB.velocity.x > Mathf.Epsilon)
{
//Moving Right
}
else if(RB.velocity.x < -Mathf.Epsilon)
{
//Moving Left
}
else
{
//Not moving left or right
}
``````

Since you are comparing floats I suggest using Mathf.Epsilon instead of 0 because it’s unlikely for a float to ever == 0 exactly due to floating point errors.