using UnityEngine;
/// <summary>
/// GAME 1303 Tier 1 — "Touch this and get hurt." Put it on spikes, saws, fire,
/// enemies, bullets — anything that damages by contact.
///
/// SETUP
/// - Needs a Collider2D on the same object. Works as a trigger OR a solid collider.
/// - Target Tag: usually "Player". Enemies use "Player"; player attacks use "Enemy".
/// - Damage: how much to subtract. Instant Kill ignores health and i-frames (pits, acid).
/// - Knockback Force: 0 for none. Direction is away from this object's center.
/// - Repeat Interval: if the player stands on a hazard, re-apply every N seconds
/// (set 0 to only hit on first contact).
/// </summary>
[RequireComponent(typeof(Collider2D))]
public class DamageOnContact : MonoBehaviour
{
[Header("Who gets hurt")]
public string targetTag = "Player";
[Header("Damage")]
public int damage = 1;
public bool instantKill = false;
[Header("Knockback")]
public float knockbackForce = 8f;
[Tooltip("Adds upward lift to knockback so it feels like a hop.")]
public float knockbackUpward = 4f;
[Header("Continuous")]
[Tooltip("Seconds between repeated hits while staying in contact. 0 = only on enter.")]
public float repeatInterval = 0.5f;
private float repeatTimer;
void OnTriggerEnter2D(Collider2D other) => TryDamage(other);
void OnCollisionEnter2D(Collision2D col) => TryDamage(col.collider);
void OnTriggerStay2D(Collider2D other) => TryRepeat(other);
void OnCollisionStay2D(Collision2D col) => TryRepeat(col.collider);
void TryRepeat(Collider2D other)
{
if (repeatInterval <= 0f) return;
repeatTimer -= Time.deltaTime;
if (repeatTimer <= 0f && TryDamage(other)) repeatTimer = repeatInterval;
}
bool TryDamage(Collider2D other)
{
if (!other.CompareTag(targetTag)) return false;
Health hp = other.GetComponent<Health>();
if (hp == null) hp = other.GetComponentInParent<Health>();
if (hp == null) return false;
bool applied;
if (instantKill) { hp.Kill(); applied = true; }
else applied = hp.TakeDamage(damage);
if (applied && knockbackForce > 0f)
{
Rigidbody2D rb = other.attachedRigidbody;
if (rb != null)
{
Vector2 dir = (other.transform.position - transform.position).normalized;
Vector2 force = dir * knockbackForce + Vector2.up * knockbackUpward;
rb.linearVelocity = Vector2.zero;
rb.AddForce(force, ForceMode2D.Impulse);
}
}
return applied;
}
}