Files
Gnome-s-Bounty/Assets/Scripts/Character.cs
T
2023-06-27 22:16:09 +03:00

140 lines
3.7 KiB
C#

using UnityEngine;
public class Character : MonoBehaviour
{
[SerializeField]
private Animator animator;
[SerializeField]
private float MovementSpeed = 1.5f;
[SerializeField]
private LayerMask _mapLayer;
private Rigidbody2D _body;
private BoxCollider2D _boxCollider;
private bool _isOnBridge;
private bool _isOnLadder;
private bool _isFalling;
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 mapElement = GetMapElement(Vector2.down);
_isOnBridge = mapElement == MapElementType.Bridge && !_isFalling;
float v_movement=0;
if (mapElement==MapElementType.Wall || _isOnLadder || _isOnBridge)
{
var leftCheck = GetMapElement(Vector2.left);
var rightCheck = GetMapElement(Vector2.right);
if(leftCheck == MapElementType.Wall) {
isAllowLeft = false;
}else
{
isAllowLeft = true;
}
if (rightCheck ==MapElementType.Wall) {
isAllowRight = false;
}else
{
isAllowRight = true;
}
isAllowVertical = false;
_isFalling = false;
float h_movement = inputHorizontal;
if (h_movement > 0 && !_facingRight)
{
FlipCharacter();
}
if (h_movement < 0 && _facingRight)
{
FlipCharacter();
}
animator.SetBool("Walk", h_movement != 0);
_isOnLadder = mapElement == MapElementType.Ladder || GetMapElement(Vector2.up) == MapElementType.Ladder;
if (_isOnLadder)
{
isAllowVertical = true;
_isOnLadder = true;
v_movement = inputVertical;
if (v_movement > 0)
{
if (GetMapElement(Vector2.up) != MapElementType.Ladder)
{
v_movement = 0;
}
}
}
_body.velocity = new Vector2(h_movement * MovementSpeed, v_movement * MovementSpeed);
}
else
{
_isFalling = true;
}
}
private MapElementType GetMapElement(Vector2 direction)
{
var raycastHit=Physics2D.BoxCast(_boxCollider.bounds.center, _boxCollider.bounds.size, 0f, direction, .1f, _mapLayer);
if (raycastHit)
{
var mapElement = raycastHit.transform.GetComponent<MapElement>();
return mapElement == null ? MapElementType.Empty : mapElement.ElementSO.ElementType;
}
else
return MapElementType.Empty;
}
private void FixedUpdate()
{
if (_isOnLadder|| _isOnBridge)
{
_body.gravityScale = 0;
}
else
{
_body.gravityScale = 1;
}
if (_isFalling)
{
if (GetMapElement(Vector2.down)==MapElementType.Ladder)
{
_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;
}
}