- Home /
How to change the player's forward direction and make turning more smooth
Hi! Thanks for taking a minute to read my question.
So I have a player model with a camera attached to it and that is controllable by the arrow keys. When I change direction, I would like the direction that the player is facing to be "forward". So if I turn to the right, I would like the forward arrow key to control the movement forward, and not the right key as it does now. How could I do this?
Also, how could I make the turning more smooth in the process? It's a little jerky and somewhat disorienting.
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/20220612201404im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Flip over an object (smooth transition) 3 Answers
How do i get the Raycast rotation? 1 Answer
Distribute terrain in zones 3 Answers
Need to rotate an object towards mouse click 1 Answer
Collision problem 4 Answers