Files
Gnome-s-Bounty/Assets/Scripts/Player/HammerThrower.cs
T
2026-06-22 15:49:58 +03:00

103 lines
2.7 KiB
C#

using System;
using UnityEngine;
public class HammerThrower : MonoBehaviour
{
[SerializeField] private Transform _spawnPoint;
[SerializeField] private GameObject hammerInHand;
[SerializeField] private float _throwSpeed = 5f;
[SerializeField] private float _throwCooldown = 1.5f;
[SerializeField] private Collider2D _playerCollider;
private GameObject _currentHammer;
private bool _hasHammer = true;
private bool _facingRight = true;
private float _cooldownTimer = 0f;
public bool HasHammer => _hasHammer;
public bool CanThrow => _hasHammer && _cooldownTimer <= 0f;
public float CooldownRemaining => Mathf.Max(0f, _cooldownTimer);
private void Awake()
{
_currentHammer = hammerInHand;
}
public void SetFacingDirection(bool facingRight)
{
_facingRight = facingRight;
}
public bool TryThrowHammer()
{
if (!CanThrow)
return false;
ThrowHammer();
return true;
}
private void ThrowHammer()
{
if (hammerInHand == null || _spawnPoint == null)
return;
_currentHammer = hammerInHand;
_currentHammer.transform.SetParent(null);
_currentHammer.transform.position = _spawnPoint.position;
_currentHammer.transform.rotation = _spawnPoint.rotation;
_hasHammer = false;
_cooldownTimer = _throwCooldown;
var hammer = _currentHammer.GetComponent<Hammer>();
if (hammer != null)
{
hammer.OnReturnedToHand += ReturnHammerToHand;
hammer.Initialize(_facingRight, _throwSpeed);
}
if (_playerCollider != null)
{
var hammerCollider = _currentHammer.GetComponent<Collider2D>();
if (hammerCollider != null)
{
Physics2D.IgnoreCollision(_playerCollider, hammerCollider);
}
}
}
private void Update()
{
if (_cooldownTimer > 0f)
{
_cooldownTimer -= Time.deltaTime;
}
}
private void ReturnHammerToHand()
{
if (_currentHammer == null || _spawnPoint == null)
return;
_currentHammer.transform.SetParent(_spawnPoint);
_currentHammer.transform.localPosition = Vector3.zero;
_currentHammer.transform.localRotation = Quaternion.identity;
var rb = _currentHammer.GetComponent<Rigidbody2D>();
if (rb != null)
{
rb.linearVelocity = Vector2.zero;
rb.angularVelocity = 0f;
}
var hammer = _currentHammer.GetComponent<Hammer>();
if (hammer != null)
{
hammer.OnReturnedToHand -= ReturnHammerToHand;
}
_hasHammer = true;
_cooldownTimer = 0f;
}
}