50 lines
1.8 KiB
C#
50 lines
1.8 KiB
C#
|
using System;
|
||
|
using UnityEngine;
|
||
|
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;
|
||
|
|
||
|
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() {
|
||
|
float moveAmount = Input.GetAxisRaw("Horizontal");
|
||
|
bool isJumping = Input.GetButtonDown("Jump");
|
||
|
|
||
|
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));
|
||
|
}
|
||
|
}
|
||
|
}
|