Files
DepthsOfGreed/Assets/Scripts/Ingame/Enemy.cs
T

157 lines
3.0 KiB
C#

using System.Collections;
using UnityEngine;
public class Enemy : MonoBehaviour, IMovementDirection
{
// Bewegungsrichtung wird von CharacterRotation verwendet.
private EnemyPathing pathing;
public Vector2 MovementDirection =>
pathing != null
? pathing.MovementDirection
: Vector2.zero;
[Header("Health")]
[SerializeField]
private float maxHealth = 100f;
private float currentHealth;
public float CurrentHealth => currentHealth;
public bool IsDead { get; private set; }
[Header("Damage Effect")]
[SerializeField]
private SpriteRenderer spriteRenderer;
[SerializeField]
private Color damageColor = Color.red;
[SerializeField]
private float damageFlashDuration = 0.15f;
private Color originalColor;
private Coroutine damageFlashCoroutine;
private CharacterRotation characterRotation;
private void Awake()
{
currentHealth = maxHealth;
// Visual und Rotation finden.
if (spriteRenderer == null)
{
spriteRenderer =
GetComponentInChildren<SpriteRenderer>();
}
if (spriteRenderer != null)
{
originalColor = spriteRenderer.color;
}
else
{
Debug.LogWarning(
"Enemy: Kein SpriteRenderer gefunden!",
this
);
}
pathing = GetComponent<EnemyPathing>();
characterRotation =
GetComponent<CharacterRotation>();
}
private void Start()
{
// Bereits vor der ersten Bewegung ausrichten.
if (characterRotation != null)
{
characterRotation.SetInitialRotation();
}
}
// LEBENSLOGIK
//
public void TakeDamage(float damage)
{
if (IsDead || damage <= 0f)
return;
currentHealth -= damage;
Debug.Log(
gameObject.name +
" erhält " + damage +
" Schaden. HP: " +
currentHealth + "/" + maxHealth
);
StartDamageFlash();
if (currentHealth <= 0f)
{
Die();
}
}
private void Die()
{
if (IsDead)
return;
IsDead = true;
Debug.Log(
gameObject.name + " wurde besiegt!"
);
Destroy(gameObject);
}
// SCHADENSEFFEKT
//
private void StartDamageFlash()
{
if (spriteRenderer == null)
return;
if (damageFlashCoroutine != null)
{
StopCoroutine(damageFlashCoroutine);
}
damageFlashCoroutine =
StartCoroutine(DamageFlash());
}
private IEnumerator DamageFlash()
{
Color flashColor = damageColor;
flashColor.a = originalColor.a;
spriteRenderer.color = flashColor;
yield return new WaitForSeconds(
damageFlashDuration
);
spriteRenderer.color = originalColor;
damageFlashCoroutine = null;
}
}