Hello! This is my first time posting. I’m taking the Apply object oriented principles Mission on the Junior programmer Pathway and I’m learning a lot. I’ve also watched a few tutorials and I have been doing some research on my own. I have seen some character controller tutorials and I was curious to give it a shot at one. It worked! Now I even can add animations on the animator and they work. But there is a problem; when the character runs into a wall or an object with a collider, it rotates as if trying to find a way around the obstacle. I’m using the Character Controller component and I have this in my script
csharp
public static PlayerController Instance { get; private set; }
[Header("References")]
private CharacterController controller;
[SerializeField] private Camera mainCamera;
[Header("Movement Settings")]
[SerializeField] private float moveSpeed = 5.0f;
[SerializeField] private float turnSpeed = 2.0f;
[Header("Input")]
private float moveInput;
private float turnInput;
private void Awake()
{
if (Instance != null)
{
Destroy(gameObject);
return;
}
Instance = this;
DontDestroyOnLoad(gameObject);
Initialize();
currentHealth = maxHealth;
}
private void Initialize()
{
if (mainCamera == null)
{
mainCamera = Camera.main;
}
controller = GetComponent<CharacterController>();
}
private void Update()
{
InputManager();
MovementManager();
}
private void InputManager()
{
moveInput = Input.GetAxisRaw("Vertical");
turnInput = Input.GetAxisRaw("Horizontal");
}
private void MovementManager()
{
Movement();
if (mainCamera == null)
{
mainCamera = Camera.main;
}
if (mainCamera != null)
{
RotateCamera();
}
}
private void Movement()
{
grounded = controller.isGrounded;
Vector3 move = new Vector3(turnInput, 0, moveInput);
move = mainCamera.transform.TransformDirection(move).normalized;
move.z *= moveSpeed;
move.x *= moveSpeed;
move.y = 0;
controller.Move(move * Time.deltaTime);
}
private void RotateCamera()
{
if (Mathf.Abs(turnInput) > 0 || Mathf.Abs(moveInput) > 0)
{
Vector3 currentLookDirection = controller.velocity.normalized;
currentLookDirection.y = 0;
currentLookDirection.Normalize();
if (currentLookDirection != Vector3.zero)
{
Quaternion targetRotation = Quaternion.LookRotation(currentLookDirection);
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, Time.deltaTime * turnSpeed);
}
}
}
This is the code relevant to moving and rotating the player and camera, I’m using a Cinemachine camera with freelook as I started my controller before Unity 6 was released. I hope my code is readable and not too much spaghetti ![]()