How to make a 2D object look in the direction of movement

When moving a 2D object it’s important to make it look in the direction it’s going. In this tutorial, we will see how to find the direction of movement and make the 2D character look in that direction.

Finding the direction of motion

You can find the direction of motion by simply subtracting the current position from the previous position.

void Start()
{
        Vector2 previousposition=transform.position;
}
void Update()  
{      
        Vector2 currentposition= transform.position;
        Vector2 direction= currentposition-previousposition;
        direction.Normalize();
        previousposition=currentposition;
}

We need to normalize the vector to get a unit vector which we will use to get the angle axis.

Finding the angle for rotation

Once you have the direction. There are two ways to rotate the sprite.

The simplest way

void Start()
{
        Vector2 previousposition=transform.position;
}
void Update()  
{      
        Vector2 currentposition= transform.position;
        Vector2 direction= currentposition-previousposition;
        direction.Normalize();
        previousposition=currentposition;
        transform.up=direction;
}

If your sprites forward direction is right, then replace transform.up to transform.right.

The next way is to find the angle and set the rotation.

Float rotationSpeed=2;

void Start()
{
        Vector2 previousposition=transform.position;
}
void Update()  
{      
        Vector2 currentposition= transform.position;
        Vector2 direction= currentposition-previousposition;
        direction.Normalize();
        previousposition=currentposition;
        float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
        Quaternion rotation = Quaternion.AngleAxis(angle, Vector3.forward);
        transform.rotation = Quaternion.Slerp(transform.rotation, rotation, rotationSpeed * Time.deltaTime);
}

Depending on your sprite you need to change the Vector3.forward to up, down or back.

If you have any other question leave it in the comment box below.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from VionixStudio

Subscribe now to keep reading and get access to the full archive.

Continue reading