c# – How can I find the direction a sprite is moving?

Myself, I’d attack it a little something like this:

public enum Direction {

public static DirectionFromTo(Vector2 from, Vector2 to) {
    Vector2 offset = to - from;
    Vector2 absolute = new Vector2(Abs(offset.x), Abs(offset.y));

    // In your code, it looks like you have a fudge factor to ignore
    // up to a +-500 change in height. You can add that like so...
    float verticalFudge = 500f;

    if (absolute.x > absolute.y - verticalFudge) {
        return offset.x > 0 ? Direction.Right : Direction.Left;

    if (absolute.y > 0) {
        return offset.y > 0 ? Direction.Down : Direction.Up;

    return Direction.None;

You can call this with your previous and current positions to get a direction of travel since last frame, or with your current and target positions to get a direction of travel to move in next.

Save the direction you were moving last frame, so you can leave it unchanged in case you have no movement and get Direction.None back from this method. That way you’ll simply keep your old facing direction instead of flickering or other bugs.

Here’s how it might look in place of your current code:

var newFacingDirection = DirectionFromTo(Position, Target.Position);

if (newFacingDirection != Direction.None)
   facingDirection = newFacingDirection;