I'm facing the problem that my chacter is spinning around itself when I try to move, that's because Im trying to make my player move in the direction of the camera, but when I move it keeps rotating around itself infinetly
Resuming my code:
public class PlayerMovement : MonoBehaviour
{
[Tooltip("This is the Time for the player rotation - it makes smooth")]
[SerializeField] private float smoothTime = 0.05f;
[SerializeField] private GameObject playerCameraObject;
private PlayerCamera playerCamera;
private CharacterController controller;
private float currentSpeedRotationing;
private Vector2 movement2D;
private Vector3 direction;
private bool IsGrounded() => controller.isGrounded;
private void Awake()
{
controller = GetComponent<CharacterController>();
}
private void Start()
{
playerCamera = playerCameraObject.GetComponent<PlayerCamera>();
}
void ApplyMovement()
{
Vector3 currentDirection = playerCamera.DirectionToMoveByCamera(direction);
controller.Move(currentDirection * currentSpeed * Time.deltaTime);
}
void ApplyRotation()
{
if (movement2D.sqrMagnitude == 0) return;
if (playerCamera.PlayerShouldRotateByCameraAngle && !playerCamera.isFirstPerson)
{
Debug.Log("sssssss");
transform.rotation = Quaternion.Euler(0.0f, playerCamera.cameraTransform.transform.eulerAngles.y, 0.0f);
}
else if (playerCamera.isFirstPerson)
{
Debug.Log("should rotate");
}
else
{
float targetAngle = Mathf.Atan2(directiion.x, direction.z) * Mathf.Rad2Deg;
float angle = Mathf.LerpAngle(transform.eulerAngles.y, targetAngle, smoothTime * Time.deltaTime);
transform.rotation = Quaternion.Euler(0.0f, angle, 0.0f);
}
}
void FixedUpdate()
{
ApplyMovement();
ApplyRotation();
}
}
public class PlayerCamera : MonoBehaviour
{
public GameObject[] cameras;
public bool PlayerShouldRotateByCameraAngle = false;
[Tooltip("As It's the main camera that rotates (cinemachinebrain), it should be the main camera")]
public Transform cameraTransform;
private int currentIndex;
public float lookSpeed = 2f;
public float lookXLimit = 90;
private float rotationX = 0;
public bool isFirstPerson = false;
private void Awake()
{
CursorLocker(true);
}
public Vector3 DirectionToMoveByCamera(Vector3 direction)
{
if (PlayerShouldRotateByCameraAngle || isFirstPerson)
{
return Quaternion.AngleAxis(cameraTransform.transform.rotation.eulerAngles.y, Vector3.up) * direction;
}
return direction;
}