using UnityEngine;
namespace BulletHellTemplate
{
///
/// Handles the damage entity that applies damage to the player upon collision.
/// Ensures damage is applied only once per instance.
///
[RequireComponent(typeof(Rigidbody), typeof(Collider))]
public class MonsterDamageEntity : MonoBehaviour
{
private CharacterTypeData monsterDamageType;
private float damageAmount;
private Rigidbody rb;
private float lifetime = 3f; // Duration before the damage entity is destroyed
private float remainingLifetime;
private bool isPaused = false;
private Vector3 storedVelocity;
private MonsterEntity monsterEntity;
private bool damageApplied = false; // Tracks whether damage has already been applied
private void Awake()
{
rb = GetComponent();
GetComponent().isTrigger = true;
remainingLifetime = lifetime;
}
///
/// Sets the damage type and amount for this damage entity.
///
/// The damage type associated with this entity.
/// The amount of damage to apply upon collision.
/// The velocity with which the damage entity should move.
/// The lifetime of the damage entity before it is destroyed.
/// The monster entity that owns this damage entity.
public void SetDamage(CharacterTypeData damageType, float damage, Vector3 velocity, float lifeTime, MonsterEntity monster)
{
monsterDamageType = damageType;
damageAmount = damage;
monsterEntity = monster;
if (lifeTime > 0)
{
lifetime = lifeTime;
}
// Set velocity only if Rigidbody is not kinematic
if (!rb.isKinematic)
{
rb.linearVelocity = velocity;
}
}
private void Update()
{
// Handle pause state
if (GameplayManager.Singleton.IsPaused())
{
if (!isPaused)
{
isPaused = true;
storedVelocity = rb.linearVelocity;
rb.isKinematic = true;
}
}
else
{
if (isPaused)
{
isPaused = false;
rb.isKinematic = false; // Restore non-kinematic state
rb.linearVelocity = storedVelocity; // Restore stored velocity
}
// Manage remaining lifetime
remainingLifetime -= Time.deltaTime;
if (remainingLifetime <= 0)
{
Destroy(gameObject);
}
}
}
private void OnTriggerEnter(Collider other)
{
// Skip collision handling if paused or damage already applied
if (GameplayManager.Singleton.IsPaused() || damageApplied || !other.CompareTag("Character"))
return;
CharacterEntity playerCharacter = other.GetComponent();
if (playerCharacter != null)
{
ApplyDamage(playerCharacter);
damageApplied = true; // Ensure damage is applied only once
}
}
///
/// Applies damage to the specified player character.
///
/// The player character to apply damage to.
private void ApplyDamage(CharacterEntity target)
{
// Adjust damage based on the monster's damage type and the player's character type.
float adjustedDamage = GameInstance.Singleton.TotalDamageWithElements(monsterDamageType, target.GetCharacterType(), damageAmount);
target.ReceiveDamage(adjustedDamage);
// Apply HP leech effect to the monster if applicable
monsterEntity.ApplyHpLeech(adjustedDamage);
}
}
}