Files
Two-World/Assets/Scripts/CharacterController2D.cs
2025-05-09 10:13:34 +09:00

115 lines
3.1 KiB
C#

using UnityEngine;
using UnityEngine.InputSystem;
[RequireComponent(typeof(Rigidbody2D))]
[RequireComponent(typeof(PlayerInput))]
public class CharacterController2D : MonoBehaviour
{
[SerializeField]
private float _moveSpeed = 5.0f;
[SerializeField]
private float _jumpForce = 5.0f;
[SerializeField]
private LayerMask _groundLayer;
[SerializeField]
private Transform _groundCheckTransformA;
[SerializeField]
private Transform _groundCheckTransformB;
[SerializeField]
private Animator _animator;
private Rigidbody2D _rigidBody;
private InputAction _moveAction;
private InputAction _jumpAction;
private Vector2 _moveInput;
private bool _isGrounded;
private bool _isFlipped;
private PlayerInput _playerInput;
void Awake()
{
_rigidBody = GetComponent<Rigidbody2D>();
_playerInput = GetComponent<PlayerInput>();
_moveAction = _playerInput.actions["Move"];
_jumpAction = _playerInput.actions["Jump"];
}
void OnEnable()
{
if (_moveAction != null)
{
_moveAction.Enable();
_moveAction.performed += OnMovePerformed;
_moveAction.canceled += OnMoveCanceled;
}
if (_jumpAction != null)
{
_jumpAction.Enable();
_jumpAction.performed += OnJumpPerformed;
}
}
void OnDisable()
{
if (_moveAction != null)
{
_moveAction.Disable();
_moveAction.performed -= OnMovePerformed;
_moveAction.canceled -= OnMoveCanceled;
}
if (_jumpAction != null)
{
_jumpAction.Disable();
_jumpAction.performed -= OnJumpPerformed;
}
}
private void OnMovePerformed(InputAction.CallbackContext context)
{
_moveInput = context.ReadValue<Vector2>();
if (_moveInput.x < 0 && !_isFlipped)
{
_isFlipped = true;
transform.localScale = new Vector3(-1.0f * transform.localScale.x, transform.localScale.y, transform.localScale.z);
}
else if (_moveInput.x > 0 && _isFlipped)
{
_isFlipped = false;
transform.localScale = new Vector3(-1.0f * transform.localScale.x, transform.localScale.y, transform.localScale.z);
}
_animator.SetBool("MoveX", true);
}
private void OnMoveCanceled(InputAction.CallbackContext context)
{
_moveInput = Vector2.zero;
_animator.SetBool("MoveX", false);
}
private void OnJumpPerformed(InputAction.CallbackContext context)
{
if (_isGrounded)
{
_rigidBody.AddForce(Vector2.up * _jumpForce, ForceMode2D.Impulse);
_animator.SetTrigger("Jump");
}
}
void Update()
{
_isGrounded = Physics2D.OverlapArea(_groundCheckTransformA.position, _groundCheckTransformB.position, _groundLayer);
_animator.SetBool("Falling", !_isGrounded);
if (_isGrounded)
{
_rigidBody.linearVelocity = new Vector2(_moveInput.x * _moveSpeed, _rigidBody.linearVelocity.y);
}
}
}