- Home /
How do I keep my character facing the direction of travel after movement stops?
I've successfully managed to make the character move and face the direction of movement, but the moment the character stops moving, they rotate back to facing one direction of the z axis. I've looked around, but can't see where I'm going wrong! Here's my script
public class Movement : MonoBehaviour {
public float speed;
public float rotationspeed;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
float horizontalInput = Input.GetAxisRaw("Horizontal");
float verticalInput = Input.GetAxisRaw("Vertical");
Vector3 movementDirection = new Vector3(horizontalInput, 0, verticalInput);
movementDirection.Normalize();
transform.Translate(movementDirection*speed*Time.deltaTime,Space.World);
if (movementDirection != Vector3.zero);
{
Quaternion toRotation = Quaternion.LookRotation(movementDirection, Vector3.up);
transform.rotation = Quaternion.RotateTowards(transform.rotation, toRotation, rotationspeed + Time.deltaTime);
}
}
}
Answer by keroltarr · Mar 04 at 05:01 PM
moving the actual rotation outside the if statement might fix that as long as the torotation variable is persistent.
Quaternion toRotation;
void Start () {
toRotation = new Quaternion(1, 0, 0, 0);
}
// Update is called once per frame
void Update () {
float horizontalInput = Input.GetAxisRaw("Horizontal");
float verticalInput = Input.GetAxisRaw("Vertical");
Vector3 movementDirection = new Vector3(horizontalInput, 0, verticalInput);
movementDirection.Normalize();
transform.Translate(movementDirection*speed*Time.deltaTime,Space.World);
if (movementDirection != Vector3.zero);
{
toRotation = Quaternion.LookRotation(movementDirection, Vector3.up);
}
transform.rotation = Quaternion.RotateTowards(transform.rotation, toRotation, rotationspeed + Time.deltaTime);
}
I tried the changes, but the same thing happens. I was wondering if the camera script I'm using was interfering, but even without it the character keeps resetting.
Your answer
Follow this Question
Related Questions
Move player according to the camera direction 1 Answer
How to incorporate a rotation towards mouse position in this script? I tried 0 Answers
How do I turn 1 objects rotation into another objects movement direction? 1 Answer
Look rotation viewing is zero warning 0 Answers
Help with rotating a sprite with mouse. 2 Answers