Get player to face the direction of movement

I have this code, and I couldn’t for the life of me figure out how to get the player sprite to face in the same direction as the way it is moving.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class movement : MonoBehaviour

    public float speed;                
    private Rigidbody2D rb;        
    float horizontal;
    float vertical;

    void Start()
        rb = GetComponent<Rigidbody2D> ();

    void Update()
        horizontal = Input.GetAxisRaw("Horizontal");
        vertical = Input.GetAxisRaw("Vertical"); 
        transform.up = GetComponent<Rigidbody>().velocity;
    private void FixedUpdate()
        rb.velocity = new Vector2(horizontal * speed, vertical * speed);

Any help would be welcome

Hi @LawnDowe, you velocity defines the direction of motion. the -z axis is the rotation axis. The only thing you need to know is, which axis is forward, y or x? - that is, which axis does your sprite face?

One other question you need to answer is whether or not you want the character to instantaneously adjust it’s rotation to match the direction of movement, or you want it to lag behind and catch up - if example, if you flip directions, do you want it to immediately rotate to match the flip, or you want it to animate around to the new direction.

I think if x is forward, you can just set transform.LookAt( rb.velocity, transform.back ) because back is -z that points to the camera - the axis to rotate on. This rotates instantly

If x is not forward then you have to start calculating angles instead of using rb.velocity.