74 lines
2.6 KiB
C#
74 lines
2.6 KiB
C#
using System;
|
|
using UnityEngine;
|
|
using UnityEngine.InputSystem;
|
|
using UnityEngine.Serialization;
|
|
|
|
[RequireComponent(typeof(BoxCollider2D))]
|
|
[RequireComponent(typeof(Rigidbody2D))]
|
|
public class PlayerController2D : MonoBehaviour {
|
|
[SerializeField] private float speed = 9;
|
|
[FormerlySerializedAs("jumpHeight")] [SerializeField] private float jumpForce = 300;
|
|
[SerializeField] private float movementSmoothing = .4f;
|
|
[SerializeField] private LayerMask whatIsGround;
|
|
[SerializeField] private bool allowAirControl = true;
|
|
[FormerlySerializedAs("GroundedRadius")] [SerializeField] private float groundedRadius = .2f;
|
|
[SerializeField] private bool isGrounded;
|
|
[SerializeField] private bool isJoystickPlayer = false;
|
|
|
|
private BoxCollider2D _boxCollider;
|
|
private Rigidbody2D _rigidbody;
|
|
private Vector2 _velocity = Vector2.zero;
|
|
|
|
private void Awake() {
|
|
_boxCollider = GetComponent<BoxCollider2D>();
|
|
_rigidbody = GetComponent<Rigidbody2D>();
|
|
}
|
|
|
|
private void FixedUpdate() {
|
|
isGrounded = false;
|
|
|
|
Collider2D[] colliders = Physics2D.OverlapCircleAll(_boxCollider.bounds.min, groundedRadius, whatIsGround);
|
|
foreach (Collider2D collider in colliders) {
|
|
if (collider != _boxCollider) {
|
|
isGrounded = true;
|
|
}
|
|
}
|
|
}
|
|
|
|
private void Update() {
|
|
// get input depending on if we aisPre using gamepad or not
|
|
float moveAmount;
|
|
bool isJumping;
|
|
if (isJoystickPlayer) {
|
|
var gamepad = Gamepad.current;
|
|
if (gamepad == null) {
|
|
Debug.LogError("A gamepad player is present but no gamepad is connected");
|
|
}
|
|
|
|
moveAmount = gamepad.leftStick.ReadValue().x;
|
|
|
|
isJumping = gamepad.aButton.wasPressedThisFrame;
|
|
} else {
|
|
var keyboard = Keyboard.current;
|
|
if (keyboard == null) {
|
|
Debug.LogError("A keyboard player is present but no keyboard is connected");
|
|
}
|
|
|
|
moveAmount = 0;
|
|
moveAmount += keyboard.dKey.isPressed ? 1 : 0;
|
|
moveAmount -= keyboard.aKey.isPressed ? 1 : 0;
|
|
|
|
isJumping = keyboard.spaceKey.wasPressedThisFrame;
|
|
}
|
|
|
|
if (isGrounded || allowAirControl) {
|
|
Vector2 target = new Vector2(moveAmount * speed, _rigidbody.velocity.y);
|
|
_rigidbody.velocity = Vector2.SmoothDamp(_rigidbody.velocity, target, ref _velocity, movementSmoothing);
|
|
}
|
|
|
|
if (isGrounded && isJumping) {
|
|
isGrounded = false;
|
|
_rigidbody.AddForce(new Vector2(0f, jumpForce));
|
|
}
|
|
}
|
|
} |