using UnityEngine;
/// <summary>
/// GAME 1303 Tier 3 — Optional helper for things the Magnet can pull. Makes a thrown
/// object hurt enemies while it's flying and become harmless once it settles.
///
/// SETUP
/// - Metal object: Sprite + Rigidbody2D (Dynamic) + Collider2D, on the "Metal" layer,
/// + this script + a DamageOnContact (Target Tag "Enemy", Damage 2, disabled — untick
/// the component). Drag the DamageOnContact into Damage While Flying.
/// - The damage turns on when thrown and off after Fly Time or when it slows down.
/// - Breakable Under Throw: destroy the object when it hits something at speed
/// (nice for scrap-metal chunks; leave off for reusable crates).
/// </summary>
[RequireComponent(typeof(Rigidbody2D))]
public class MetalObject : MonoBehaviour
{
public DamageOnContact damageWhileFlying;
public float flyTime = 1.5f;
public float settledSpeed = 1.5f;
public bool breakOnImpact = false;
public GameObject breakEffectPrefab;
public bool IsFlying { get; private set; }
public bool IsHeld { get; private set; }
private Rigidbody2D rb;
private float flyTimer;
void Awake()
{
rb = GetComponent<Rigidbody2D>();
if (damageWhileFlying != null) damageWhileFlying.enabled = false;
}
public void OnGrabbed(MagnetPull by) { IsHeld = true; IsFlying = false; SetDamage(false); }
public void OnDropped() { IsHeld = false; }
public void OnThrown()
{
IsHeld = false;
IsFlying = true;
flyTimer = flyTime;
SetDamage(true);
}
void Update()
{
if (!IsFlying) return;
flyTimer -= Time.deltaTime;
if (flyTimer <= 0f || rb.linearVelocity.magnitude < settledSpeed)
{
IsFlying = false;
SetDamage(false);
}
}
void OnCollisionEnter2D(Collision2D col)
{
if (!IsFlying || !breakOnImpact) return;
if (breakEffectPrefab != null) Instantiate(breakEffectPrefab, transform.position, Quaternion.identity);
Destroy(gameObject);
}
void SetDamage(bool on) { if (damageWhileFlying != null) damageWhileFlying.enabled = on; }
}