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!