using UnityEngine; using UnityEngine.InputSystem; [RequireComponent(typeof(CharacterController))] public class PlayerMovement : MonoBehaviour { public float playerSpeed = 10.0f; private float earthSpeed = 10f; private float jumpHeight = 2.5f; private float gravityValue = -9.81f; private CharacterController controller; private Vector3 playerVelocity; private bool groundedPlayer; private float xRotation = 0f; [Header("Input Actions")] public InputActionReference moveAction; public InputActionReference jumpAction; [Header("Camera Settings")] public Transform playerCamera; public float mouseSensitivity = 3f; [Header("Ground Checker")] public Transform groundCheck; public float groundDistance = 0.4f; public LayerMask groundMask; private void Awake() { controller = gameObject.GetComponent(); Cursor.lockState = CursorLockMode.Locked; Cursor.visible = false; } private void Start() { SetPlayerRandomSpeed(); earthSpeed = playerSpeed; } private void OnEnable() { moveAction.action.Enable(); jumpAction.action.Enable(); } private void OnDisable() { moveAction.action.Disable(); jumpAction.action.Disable(); } void Update() { if (MenuController.Instance.isPaused) return; MoveMouse(); PlayerJump(); MovePlayer(); } private void MoveMouse() { float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity; float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity; xRotation -= mouseY; xRotation = Mathf.Clamp(xRotation, -80f, 80f); playerCamera.localRotation = Quaternion.Euler(xRotation, 0f, 0f); transform.Rotate(Vector3.up * mouseX); } private void PlayerJump() { groundedPlayer = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask); if (groundedPlayer && playerVelocity.y < 0) { playerVelocity.y = 0f; } if (jumpAction.action.triggered && groundedPlayer) { playerVelocity.y = Mathf.Sqrt(jumpHeight * -2.0f * gravityValue); } } private void MovePlayer() { float horizontal = Input.GetAxis("Horizontal"); float vertical = Input.GetAxis("Vertical"); Vector3 move = transform.right * horizontal + transform.forward * vertical; controller.Move(move * playerSpeed * Time.deltaTime); playerVelocity.y += gravityValue * Time.deltaTime; controller.Move(playerVelocity * Time.deltaTime); } [ContextMenu("Set player random speed")] public void SetPlayerRandomSpeed() { playerSpeed = Random.Range(8, 15); earthSpeed = playerSpeed; } public void SetPlayerEarthSpeed() { playerSpeed = earthSpeed; gravityValue = -9.81f; } public void SetPlayerLunarSpeed() { playerSpeed *= Mathf.Sqrt(1.62f / 9.81f); gravityValue = -1.62f; } }