using UnityEngine; using UnityEngine.InputSystem; public class PlayerControllerV2 : MonoBehaviour { private CharacterController m_CharacterController; private Camera m_Camera; private bool m_IsGrounded = false; public float m_LookSensitivity = 25f; public float m_PlayerSpeed = 10f; private Vector2 m_MoveInput = Vector2.zero; private Vector2 m_LookInput = Vector2.zero; private Vector3 m_Velocity = Vector3.zero; public float m_MaxSpeed = 5f; void Awake() { m_CharacterController = GetComponent(); m_Camera = GetComponentInChildren(); Cursor.lockState = CursorLockMode.Locked; } void FixedUpdate() { m_IsGrounded = false; RaycastHit hit; // TODO: Use to see if on train later and ground angle if that's relevant if (Physics.Raycast(transform.position, Vector3.down, out hit, 1.1f)) { m_IsGrounded = true; } Look(); Move(); } private void Look() { m_CharacterController.transform.Rotate(Vector3.up * m_LookInput.x * m_LookSensitivity * Time.deltaTime); float pitchRotation = m_Camera.transform.eulerAngles.x; if (pitchRotation > 270) pitchRotation -= 360; pitchRotation -= m_LookInput.y * m_LookSensitivity * Time.deltaTime; //pitchRotation = Mathf.Clamp(pitchRotation, -90f, 90f); m_Camera.transform.localRotation = Quaternion.Euler(pitchRotation, 0f, 0f); } private void Move() { Vector3 direction = transform.right * m_MoveInput.x + transform.forward * m_MoveInput.y; m_Velocity += -transform.up * 9.81f * Time.deltaTime; // Gravity // Reset negative velocity when landed if (m_IsGrounded && m_Velocity.y < 0) { m_Velocity.y = -1 * Time.deltaTime; } // Apply input to velocity only when on the ground if (m_IsGrounded) { m_Velocity += direction * m_PlayerSpeed * Time.deltaTime; } // Apply friction when on the ground and not moving if (m_IsGrounded && m_MoveInput.magnitude < .1f /*dead zone*/) { m_Velocity.x /= 1.1f; m_Velocity.z /= 1.1f; } m_CharacterController.Move(m_Velocity * Time.deltaTime); } void OnJump() { if (m_IsGrounded) { m_Velocity.y = 10; m_IsGrounded = false; } } void OnMove(InputValue value) { m_MoveInput = value.Get(); } void OnLook(InputValue value) { m_LookInput = value.Get(); } }