133 lines
3.3 KiB
C#
133 lines
3.3 KiB
C#
using UnityEngine;
|
|
|
|
public class Character : MonoBehaviour
|
|
{
|
|
[SerializeField]
|
|
private Animator animator;
|
|
[SerializeField]
|
|
private float MovementSpeed = 1.5f;
|
|
[SerializeField]
|
|
private LayerMask ladderLayer;
|
|
[SerializeField]
|
|
private LayerMask groundLayer;
|
|
[SerializeField]
|
|
private float distance;
|
|
private bool _isOnLadder;
|
|
private Rigidbody2D _body;
|
|
private BoxCollider2D _boxCollider;
|
|
private bool _isFall;
|
|
private bool _facingRight = true;
|
|
|
|
|
|
protected bool isAllowVertical = true;
|
|
protected bool isAllowRight=true;
|
|
protected bool isAllowLeft= true;
|
|
|
|
private void Start()
|
|
{
|
|
_body = GetComponent<Rigidbody2D>();
|
|
_boxCollider = GetComponent<BoxCollider2D>();
|
|
}
|
|
|
|
protected void MoveTo(float inputHorizontal,float inputVertical)
|
|
{
|
|
var groundCheck = CheckBounds(Vector2.down, groundLayer);
|
|
|
|
float v_movement=0;
|
|
if (groundCheck || _isOnLadder)
|
|
{
|
|
var leftCheck = CheckBounds(Vector2.left, groundLayer);
|
|
var rightCheck = CheckBounds(Vector2.right, groundLayer);
|
|
if(leftCheck.collider!=null) {
|
|
isAllowLeft = false;
|
|
}else
|
|
{
|
|
isAllowLeft = true;
|
|
}
|
|
if (rightCheck.collider != null) {
|
|
isAllowRight = false;
|
|
}else
|
|
{
|
|
isAllowRight = true;
|
|
}
|
|
|
|
isAllowVertical = false;
|
|
_isFall = false;
|
|
float h_movement = inputHorizontal;
|
|
if (h_movement > 0 && !_facingRight)
|
|
{
|
|
FlipCharacter();
|
|
}
|
|
if (h_movement < 0 && _facingRight)
|
|
{
|
|
FlipCharacter();
|
|
}
|
|
|
|
animator.SetBool("Walk", h_movement != 0);
|
|
|
|
if (CheckBounds(Vector2.down, ladderLayer))
|
|
{
|
|
isAllowVertical = true;
|
|
_isOnLadder = true;
|
|
v_movement=inputVertical;
|
|
|
|
if (v_movement > 0)
|
|
{
|
|
if (!CheckBounds(Vector2.up,ladderLayer))
|
|
{
|
|
v_movement = 0;
|
|
}
|
|
}
|
|
}
|
|
else
|
|
{
|
|
_isOnLadder = false;
|
|
}
|
|
_body.velocity = new Vector2(h_movement * MovementSpeed, v_movement * MovementSpeed);
|
|
}
|
|
else
|
|
{
|
|
_isFall = true;
|
|
}
|
|
}
|
|
|
|
private RaycastHit2D CheckBounds(Vector2 direction,LayerMask layer)
|
|
{
|
|
return Physics2D.BoxCast(_boxCollider.bounds.center, _boxCollider.bounds.size, 0f, direction, .1f, layer);
|
|
}
|
|
|
|
|
|
private void FixedUpdate()
|
|
{
|
|
if (_isOnLadder)
|
|
{
|
|
|
|
_body.gravityScale = 0;
|
|
}
|
|
else
|
|
{
|
|
_body.gravityScale = 1;
|
|
}
|
|
if (_isFall)
|
|
{
|
|
if (CheckBounds(Vector2.down,ladderLayer))
|
|
{
|
|
_isOnLadder = true;
|
|
}
|
|
_body.velocity = new Vector2(0, _body.velocity.y);
|
|
animator.SetBool("Walk", false);
|
|
}
|
|
}
|
|
|
|
private void FlipCharacter()
|
|
{
|
|
Vector3 currentScale = gameObject.transform.localScale;
|
|
currentScale.x *= -1;
|
|
gameObject.transform.localScale = currentScale;
|
|
|
|
_facingRight = !_facingRight;
|
|
}
|
|
|
|
|
|
}
|