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

112 lines
2.9 KiB
C#

using UnityEngine;
public class Hammer : MonoBehaviour
{
[SerializeField] private float _lifespan = 5f;
[SerializeField] private float _stunDuration = 1f;
[SerializeField] private float _impactNoiseRadius = 10f;
[SerializeField] private bool _emitNoiseOnImpact = true;
public event System.Action OnReturnedToHand;
private float _lifeTimer;
private Vector2 _velocity;
private bool _facingRight;
private Rigidbody2D _rigidbody;
private bool _hasCollided = false;
private bool _isThrown = false;
private void Awake()
{
_rigidbody = GetComponent<Rigidbody2D>();
_lifeTimer = _lifespan;
}
public void Initialize(bool facingRight, float speed)
{
_facingRight = facingRight;
_velocity = new Vector2(facingRight ? speed : -speed, 0);
_isThrown = true;
if (_rigidbody != null)
{
_rigidbody.linearVelocity = _velocity;
_rigidbody.angularVelocity = 0f;
}
}
private void Update()
{
// Self-destruct after lifespan expires
_lifeTimer -= Time.deltaTime;
if (_lifeTimer <= 0)
{
Destroy(gameObject);
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (_hasCollided)
return;
_hasCollided = true;
// Check for enemy collision (stun)
var enemy = collision.gameObject.GetComponent<Character>();
if (enemy != null)
{
HandleEnemyCollision(enemy, collision.relativeVelocity);
EmitImpactNoise(collision.GetContact(0).point);
ReturnToHand();
return;
}
// Check for breakable wall collision
var mapElement = collision.collider.GetComponent<MapElement>();
if (mapElement != null && mapElement is BreakableWall)
{
mapElement.Hit();
EmitImpactNoise(collision.GetContact(0).point);
ReturnToHand();
return;
}
// Fallback: return hammer on any collision
EmitImpactNoise(collision.GetContact(0).point);
ReturnToHand();
}
private void HandleEnemyCollision(Character enemy, Vector2 impactVelocity)
{
// Apply stun to enemy
var enemyAI = enemy as EnemyAI;
if (enemyAI != null)
{
enemyAI.OnHitByHammer(_stunDuration);
}
}
private void EmitImpactNoise(Vector2 position)
{
if (!_emitNoiseOnImpact)
return;
// Check if NoiseSystem exists and emit noise
var noiseSystem = NoiseSystem.Instance;
if (noiseSystem != null)
{
noiseSystem.Emit(position, _impactNoiseRadius);
}
}
private void ReturnToHand()
{
_isThrown = false;
if (OnReturnedToHand != null)
{
OnReturnedToHand.Invoke();
}
}
}