Hi Im trying to make a first person controller with Character controller and the new input system. One problem appear in delta[mouse] or delta[pointer]is the the Vector2 returns a value when i press any button of the mouse, this cause that the player camera rotate a little bit. Example:
These are my actions:
And this is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
[RequireComponent (typeof(CharacterController))]
public class PlayerCharacterController : MonoBehaviour
{
private Vector2 moveInput = Vector2.zero;
private Vector2 rotationInput = Vector2.zero;
private float cameraVerticalAngle = 0f;
// ****** Character Controler
private CharacterController characterController;
// ****** Input Actions
private PlayerInputActions inputActions;
[Header("Refrerences")]
[Tooltip("Reference for the main camare used for the player")]
public Camera playerCamera;
[Header("General")]
[SerializeField] private float walkSpeed = 12f;
[SerializeField] private float gravityDownForce = 20f;
[Header("Movement")]
[SerializeField] private float speedOnGround;
[Header("Rotation")]
[SerializeField] private float rotationSpeed = 60f;
[Header("Jump")]
[SerializeField] private float jumpForce;
private void Awake()
{
characterController = GetComponent<CharacterController>();
inputActions = new PlayerInputActions();
inputActions.PlayerControlls.Move.performed += ctx => moveInput = ctx.ReadValue<Vector2>();
inputActions.PlayerControlls.CameraMove.performed += ctx => rotationInput = ctx.ReadValue<Vector2>();
}
private void Start()
{
//Cursor.lockState = CursorLockMode.Locked;
}
private void Update()
{
Move(inputActions.PlayerControlls.Move.ReadValue<Vector2>());
Look(inputActions.PlayerControlls.CameraMove.ReadValue<Vector2>());
}
private void Move(Vector2 direction)
{
if (direction.sqrMagnitude < 0.05)
return;
float scaledMoveSpeed = walkSpeed * Time.deltaTime;
Vector3 move = Quaternion.Euler(0, transform.eulerAngles.y, 0) * new Vector3(direction.x, 0, direction.y);
transform.position += move * scaledMoveSpeed;
}
private void Look(Vector2 rotate)
{
if (rotationInput.sqrMagnitude < 0.05)
return;
// ****** Limit the X rotation force amount
rotate.x = Mathf.Clamp(rotate.x, -10f, 10f);
rotate.y = Mathf.Clamp(rotate.y, -10f, 10f);
// ****** Delta rotation in Quaternions
rotationInput.x = rotate.x * rotationSpeed * Time.deltaTime;
rotationInput.y = rotate.y * rotationSpeed * Time.deltaTime;
// ****** Vertical rotation in degrees
cameraVerticalAngle += rotationInput.y;
cameraVerticalAngle = Mathf.Clamp(cameraVerticalAngle, -70f,70f);
transform.Rotate(0, rotationInput.x, 0);
playerCamera.transform.localRotation = Quaternion.Euler(-cameraVerticalAngle, 0f, 0f);
}
private void OnEnable()
{
inputActions.Enable();
}
private void OnDisable()
{
inputActions.Disable();
}
}