How do I get the direction of a moving object?

Hello, how do I get the direction of a moving object in Unity2D? I have already tried with velocity, but failed. My second attempt was to create a vector between the point of the previous update and the current position, but the values were so small that the vector was not 0 only every few updates. Are there other ways?

How is the object being moved? It sounds like you might be manually moving it every few frames if you aren’t getting non-zero values with velocity or comparing positions. If that is the case then your object wont be moving on most frames, so you cant really measure its movement reliably, and you’d be better off moving it differently. If you cant fix that, you could try using the current facing of the object using transform.forward, transform.up or transform.right? Or possibly something similar to what you tried with comparing positions, but only change the stored previous position if it changes, then you will get the last direction the object moved:

public class MoveDirectionTracker : MonoBehaviour {
    Vector3 previousPosition;
    Vector3 lastMoveDirection;
    private void Start() {
        previousPosition = transform.position;
        lastMoveDirection = Vector3.zero;
    }

    private void FixedUpdate() {
        if(transform.position != previousPosition) {
            lastMoveDirection = (transform.position - previousPosition).normalized;
            previousPosition = transform.position;
        }
    }
}

My idea is to “flick” the ball across the screen by dragging the mouse, like a slingshot.

void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            startpoint = camera.ScreenToWorldPoint(Input.mousePosition);
            startpoint.z = 23;
            rb.velocity = Vector2.zero;
            rb.gravityScale = 0;

        }
        if (Input.GetMouseButtonUp(0))
        {
            endpoint = camera.ScreenToWorldPoint(Input.mousePosition);
            endpoint.z = 23;
            ballforce = new Vector2(startpoint.x - endpoint.x, startpoint.y - endpoint.y);
            rb.gravityScale = Gravitys;
            rb.AddForce(ballforce * BallPower, ForceMode2D.Impulse);
        }

        if (!Input.GetMouseButton(0))

        {
            float angle = Mathf.Atan2(transform.position.y - mPosition.y, transform.position.x - mPosition.x);
            if (transform.position - mPosition != new Vector3(0, 0, 0))
            {
                transform.rotation = Quaternion.Euler(0, 0, angle);
                Vector3 Test = transform.position - mPosition;

                UnityEngine.Debug.Log(Test);
                mPosition = transform.position;
            }


        }
    }

But when I want to get the direction of the Ball, to rotate it that I can squeeze it in that way, the angle is every time 0 degrees, because the current position and the previous position is 0.