Files
AppleHillsProduction/Assets/Scripts/Minigames/FortFight/Projectiles/TrashPiece.cs
Michal Pikulski 0b8d2a279f Working MVP
2025-12-04 02:16:47 +01:00

81 lines
3.0 KiB
C#

using Core;
using UnityEngine;
namespace Minigames.FortFight.Projectiles
{
/// <summary>
/// Component for individual trash pieces spawned by TrashBagProjectile.
/// Deals pre-configured damage on collision with blocks, spawns impact effect, then auto-cleans up after timeout.
/// </summary>
public class TrashPiece : MonoBehaviour
{
[Header("Visual Effects")]
[Tooltip("Impact effect prefab spawned on block collision")]
[SerializeField] private GameObject impactEffectPrefab;
private float damage;
private bool hasHit = false;
private void Start()
{
// Get configuration from settings
var settings = GameManager.GetSettingsObject<AppleHills.Core.Settings.IFortFightSettings>();
damage = settings?.TrashPieceDamage ?? 5f;
float lifetime = settings?.TrashPieceLifetime ?? 5f;
// Auto-cleanup after configured timeout
Destroy(gameObject, lifetime);
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (hasHit) return;
// Check if hit a fort block
var block = collision.gameObject.GetComponent<Fort.FortBlock>();
if (block != null)
{
hasHit = true;
// Deal damage
block.TakeDamage(damage);
Logging.Debug($"[TrashPiece] Dealt {damage} damage to {block.gameObject.name}");
// Spawn impact effect at collision point
if (impactEffectPrefab != null && collision.contacts.Length > 0)
{
Vector2 impactPoint = collision.contacts[0].point;
GameObject effect = Instantiate(impactEffectPrefab, impactPoint, Quaternion.identity);
// Dynamically determine cleanup time from particle system
float lifetime = GetEffectLifetime(effect);
Destroy(effect, lifetime);
}
}
}
/// <summary>
/// Get the lifetime of an effect by reading particle system StartLifetime.
/// Falls back to 2 seconds if no particle system found.
/// </summary>
private float GetEffectLifetime(GameObject effect)
{
// Try to read from ParticleSystem
ParticleSystem ps = effect.GetComponent<ParticleSystem>();
if (ps != null)
{
return ps.main.startLifetime.constantMax + 0.5f; // Add small buffer
}
// Try to read from child particle systems
ParticleSystem childPs = effect.GetComponentInChildren<ParticleSystem>();
if (childPs != null)
{
return childPs.main.startLifetime.constantMax + 0.5f;
}
// Fallback for non-particle effects
return 2f;
}
}
}