proto_top_down/Assets/Scripts/MeleeEnemy.cs

100 lines
2.3 KiB
C#
Raw Normal View History

using UnityEngine;
[RequireComponent(typeof(Health))]
public class MeleeEnemy : MonoBehaviour
{
enum State
{
Wandering = 0,
Seeking = 1,
Dead = 2,
};
//private State _currentState;
private System.Action updateFunc;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
//_currentState = State::Wandering;
updateFunc = DoWander;
var h = GetComponent<Health>();
h.OnDeath += ProcessDeath;
}
#region Wander
[Header("Wander")]
public float dirChangeDuration = 2;
public float wanderSpeed;
private Vector3 wanderDir;
private float _lastDirChange = -2;
private void DoWander()
{
if (_lastDirChange + dirChangeDuration < Time.time)
{
wanderDir.x = Random.Range(-1f, 1f);
wanderDir.y = Random.Range(-1f, 1f);
_lastDirChange = Time.time;
//Debug.Log($"New wander dir: {wanderDir}");
}
transform.position += wanderDir * wanderSpeed * Time.deltaTime;
}
#endregion Wander
#region Seek
[Header("Seek")]
public float seekSpeed = 2;
private Transform _target;
private void DoSeek()
{
var dir = (_target.position - transform.position).normalized;
transform.position += dir * seekSpeed * Time.deltaTime;
}
#endregion Seek
private void DoSleep()
{
}
// Update is called once per frame
private void Update()
{
updateFunc();
}
private void ProcessDeath()
{
// TODO: effects
Destroy(gameObject);
}
private void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("Player"))
{
//Debug.Log("Player is in our sphere");
_target = other.transform;
updateFunc = DoSeek;
}
}
private void OnCollisionEnter2D(Collision2D other)
{
if (other.collider.CompareTag("Player"))
{
Debug.Log("We have hit the player!");
var health = other.gameObject.GetComponent<Health>();
if (health != null)
{
updateFunc = DoSleep;
Destroy(gameObject);
health.DealDamage(5);
}
}
}
}