Files
Gnome-s-Bounty/Assets/Scripts/Player.cs
T
2024-01-08 08:42:36 +02:00

145 lines
3.4 KiB
C#

using System;
using UnityEngine;
public class Player : Character
{
[SerializeField]
private Transform _hammerSpawnPoint;
[SerializeField]
private GameObject _hammerPrefab;
[SerializeField]
private Sprite _regularSprite;
[SerializeField]
private Sprite _noHammerSprite;
public int Lives=3;
private int _hammerSpeed = 5;
private int _totalCoins = 0;
private bool _hasKey = false;
public int TotalCoins => _totalCoins;
public static Player Instance { get; private set; }
private GameObject _hammer;
private bool _isHoldingHammer = true;
public event EventHandler<TreasureType> OnPlayerTakeItem;
private InputActions _inputActions;
private void Awake()
{
if (Instance != null)
{
Destroy(gameObject);
Debug.Log("There's more than one player instance");
return;
}
PlayerPrefs.SetString("lastExitName", string.Empty);
Instance = this;
DontDestroyOnLoad(gameObject);
_inputActions = new InputActions();
}
private void OnEnable()
{
_inputActions.Enable();
}
private void OnDisable()
{
_inputActions.Disable();
}
public void AddCoin()
{
_totalCoins++;
OnPlayerTakeItem?.Invoke(this,TreasureType.Coin);
print($"player have {_totalCoins} coins");
}
public void SetKey()
{
OnPlayerTakeItem?.Invoke(this, TreasureType.Key);
print($"player have key");
_hasKey = true;
}
public void RemoveKey()
{
_hasKey = false;
}
public bool IsHasKey()
{
return _hasKey;
}
private void Update()
{
if (_hammer == null && !_isHoldingHammer)
{
_spriteRenderer.sprite = _regularSprite;
_isHoldingHammer = true;
}
if (FireButtonPressed() && !_isFalling)
{
if (_hammer == null)
{
_animator.SetTrigger("Body_ThrowHammer");
}
}
var move = _inputActions.Player.Movement.ReadValue<Vector2>();
base.MoveTo(move.x, isAllowVertical ? move.y : 0);
}
private bool FireButtonPressed()
{
return _inputActions.Player.Fire.triggered && _inputActions.Player.Fire.ReadValue<float>() > 0;
}
public void ThrowHammerObject()
{
_isHoldingHammer = false;
_spriteRenderer.sprite = _noHammerSprite;
_hammer = Instantiate(_hammerPrefab, _hammerSpawnPoint.position, _hammerSpawnPoint.rotation);
_hammer.transform.localScale = new Vector2(_hammer.transform.localScale.x * (_facingRight ? 1 : -1), _hammer.transform.localScale.y);
_hammer.GetComponent<Rigidbody2D>().velocity = new Vector2(gameObject.transform.localScale.x * _hammerSpeed, 0);
}
protected override void SetWalkingAnimation(bool isWalking)
{
_bonesBack.SetActive(false);
_bonesSide.SetActive(true);
_animator.SetBool("Legs_Walk",isWalking);
_animator.SetBool("Body_Walk", isWalking);
}
protected override void SetClimbingAnimation(bool isClimbing)
{
if (isClimbing)
{
_bonesBack.SetActive(true);
_bonesSide.SetActive(false);
}
_animator.SetBool("Climb", isClimbing);
}
protected void OnDeath()
{
Lives--;
if (Lives==0)
{
print("game over");
}
}
}