using UnityEngine; using UnityEngine.InputSystem; [RequireComponent(typeof(Rigidbody2D))] [RequireComponent(typeof(BoxCollider2D))] public class PlayerPlatformerController : MonoBehaviour { [SerializeField] private InputActionAsset inputActions; [SerializeField] private string actionMapName = "Player"; [SerializeField] private string moveActionName = "Move"; [SerializeField] private string jumpActionName = "Jump"; [SerializeField] private float moveSpeed = 6f; [SerializeField] private float jumpImpulse = 8f; [SerializeField] private LayerMask groundMask = ~0; [SerializeField] private float groundCheckDistance = 0.05f; private Rigidbody2D body; private BoxCollider2D bodyCollider; private InputAction moveAction; private InputAction jumpAction; private void Awake() { body = GetComponent(); bodyCollider = GetComponent(); } private void OnEnable() { if (inputActions == null) { Debug.LogError("PlayerPlatformerController missing InputActionAsset reference.", this); return; } var map = inputActions.FindActionMap(actionMapName, true); moveAction = map.FindAction(moveActionName, true); jumpAction = map.FindAction(jumpActionName, true); moveAction.Enable(); jumpAction.Enable(); jumpAction.performed += OnJumpPerformed; } private void OnDisable() { if (jumpAction != null) { jumpAction.performed -= OnJumpPerformed; jumpAction.Disable(); } if (moveAction != null) { moveAction.Disable(); } } private void FixedUpdate() { if (moveAction == null) { return; } var input = moveAction.ReadValue(); var velocity = body.linearVelocity; velocity.x = input.x * moveSpeed; body.linearVelocity = velocity; } private void OnJumpPerformed(InputAction.CallbackContext context) { if (!IsGrounded()) { return; } var velocity = body.linearVelocity; velocity.y = 0f; body.linearVelocity = velocity; body.AddForce(Vector2.up * jumpImpulse, ForceMode2D.Impulse); } private bool IsGrounded() { var bounds = bodyCollider.bounds; var checkSize = new Vector2(bounds.size.x * 0.9f, groundCheckDistance * 2f); var checkCenter = new Vector2(bounds.center.x, bounds.min.y - groundCheckDistance); var hits = Physics2D.OverlapBoxAll(checkCenter, checkSize, 0f, groundMask); for (var i = 0; i < hits.Length; i++) { var hit = hits[i]; if (hit != null && hit != bodyCollider) { return true; } } return false; } }