using UnityEngine; using UnityEngine.InputSystem; [RequireComponent(typeof(Rigidbody))] public class PlayerController : MonoBehaviour { //Input fields private FarmerInputActions farmerInputActions; private InputAction movement; //physics settings private Rigidbody rb; [SerializeField] private float movementForce = 1f; [SerializeField] private float jumpForce = 10; [SerializeField] private float maxSpeed = 5f; private Vector3 forceDirection = Vector3.zero; [SerializeField] private Camera playerCamera; private void Awake() { rb = this.GetComponent(); farmerInputActions = new FarmerInputActions(); } private void OnEnable() { //no event needed for movement //these values will be constantly read movement = farmerInputActions.Player.Move; movement.Enable(); //triggered by events farmerInputActions.Player.Jump.performed += DoJump; farmerInputActions.Player.Jump.Enable(); } private void OnDisable() { movement.Disable(); farmerInputActions.Player.Jump.Disable(); } private void FixedUpdate() { //read input values forceDirection += movement.ReadValue().x * GetCameraRight(playerCamera); forceDirection += movement.ReadValue().y * GetCameraForward(playerCamera); forceDirection *= movementForce; //apply the force rb.AddForce(forceDirection, ForceMode.Impulse); //reset for next frame forceDirection = Vector3.zero; //extra gravity to feel less floaty? if (rb.velocity.y < 0) rb.velocity += Vector3.down * 10 * Time.fixedDeltaTime; //limit speed - but only in the horizontal Vector3 horizontalVelocity = rb.velocity; horizontalVelocity.y = 0; if (horizontalVelocity.sqrMagnitude > maxSpeed * maxSpeed) rb.velocity = horizontalVelocity.normalized * maxSpeed + Vector3.up * rb.velocity.y; MoveLookAt(); } private void DoJump(InputAction.CallbackContext obj) { if (IsGrounded()) { forceDirection += Vector3.up * jumpForce; } } private void MoveLookAt() { Vector3 direction = rb.velocity; direction.y = 0; if (movement.ReadValue().magnitude > 0.1f && direction.magnitude > 0.1f) this.rb.rotation = Quaternion.LookRotation(direction, Vector3.up); else rb.angularVelocity = Vector3.zero; } //Gets forward direction of camera relative to the horizontal private Vector3 GetCameraForward(Camera camera) { Vector3 forward = camera.transform.forward; forward.y = 0; return forward.normalized; } //Gets right direction of camera relative to the horizontal private Vector3 GetCameraRight(Camera camera) { Vector3 right = camera.transform.right; right.y = 0; return right.normalized; } private bool IsGrounded() { Ray ray = new Ray(this.transform.position + Vector3.up * 0.25f, Vector3.down); if (Physics.Raycast(ray, out RaycastHit hit, 0.3f)) return true; else return false; } }