Added basic features
This commit is contained in:
96
Assets/Scripts/CharacterController2D.cs
Normal file
96
Assets/Scripts/CharacterController2D.cs
Normal file
@@ -0,0 +1,96 @@
|
||||
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;
|
||||
|
||||
private Rigidbody2D _rigidBody;
|
||||
private InputAction _moveAction;
|
||||
private InputAction _jumpAction;
|
||||
|
||||
private Vector2 _moveInput;
|
||||
private bool _isGrounded;
|
||||
|
||||
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>();
|
||||
}
|
||||
|
||||
private void OnMoveCanceled(InputAction.CallbackContext context)
|
||||
{
|
||||
_moveInput = Vector2.zero;
|
||||
}
|
||||
|
||||
private void OnJumpPerformed(InputAction.CallbackContext context)
|
||||
{
|
||||
if (_isGrounded)
|
||||
{
|
||||
_rigidBody.AddForce(Vector2.up * _jumpForce, ForceMode2D.Impulse);
|
||||
}
|
||||
}
|
||||
|
||||
void Update()
|
||||
{
|
||||
_isGrounded = Physics2D.OverlapArea(_groundCheckTransformA.position, _groundCheckTransformB.position, _groundLayer);
|
||||
|
||||
if (_isGrounded)
|
||||
{
|
||||
_rigidBody.linearVelocity = new Vector2(_moveInput.x * _moveSpeed, _rigidBody.linearVelocity.y);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user