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
Answer by streeetwalker · Apr 04, 2020 at 12:30 PM
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.
Your answer
Follow this Question
Related Questions
How to adjust a GameObject's rotation to face it's moving direction ? 0 Answers
How to not execute certain line of code. 2 Answers
Character movement that ends with a specific facing 0 Answers
Struggling to get the rotation the player is moving in. 1 Answer
How do I rotate my object back to the world's up direction whilst keeping it's forward direction? 0 Answers