- Home /
How to change the forward direction of a player and make turning smoother
I'm fairly new to Unity and C#, but I am willing to learn. I would appreciate any help!
I have a player with a camera which follows it, and can be controlled by the arrow keys. When the player changes directions, I would like for the new direction the player is facing to be "forward", so the forward arrow key makes the player move in the direction it is facing. How could I go about that?
I would also like to make the turning of the character more smooth so that it's not so disorienting. How could I do that also? I'm using Unity version 2019.1.1f1.
Here's my code: using System.Collections; using System.Collections.Generic; using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float turnSpeed = 1f;
Animator m_Animator;
Rigidbody m_Rigidbody;
Vector3 m_Movement;
Quaternion m_Rotation = Quaternion.identity;
void Start()
{
m_Animator = GetComponent<Animator>();
m_Rigidbody = GetComponent<Rigidbody>();
}
void FixedUpdate()
{
float horizontal = Input.GetAxis("Horizontal");
float vertical = Input.GetAxis("Vertical");
m_Movement.Set(horizontal, 0f, vertical);
m_Movement.Normalize();
bool hasHorizontalInput = !Mathf.Approximately(horizontal, 0f);
bool hasVerticalInput = !Mathf.Approximately(vertical, 0f);
bool isWalking = hasHorizontalInput || hasVerticalInput;
m_Animator.SetBool("IsWalking", isWalking);
Vector3 desiredForward = Vector3.RotateTowards(transform.forward, m_Movement, turnSpeed * Time.deltaTime, 0f);
m_Rotation = Quaternion.LookRotation(desiredForward);
}
void OnAnimatorMove()
{
m_Rigidbody.MovePosition(m_Rigidbody.position + m_Movement * m_Animator.deltaPosition.magnitude);
m_Rigidbody.MoveRotation(m_Rotation);
}
}
Thanks in advance!
Your answer
![](https://koobas.hobune.stream/wayback/20220612201405im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Flip over an object (smooth transition) 3 Answers
How can I rotate my player with a Joystick? 0 Answers
Wrong rotation while moving 1 Answer
Multiple Cars not working 1 Answer
Player mouse rotation 2 Answers