105 lines
3.0 KiB
C#
105 lines
3.0 KiB
C#
using UnityEngine;
|
|
using Code.Gameplay.Player;
|
|
using DG.Tweening;
|
|
|
|
namespace Code.Gameplay.Enemies
|
|
{
|
|
public class BasicEnemy : MonoBehaviour, IEnemy
|
|
{
|
|
[SerializeField] private float _speed = 2f;
|
|
[SerializeField] private float _patrolDistance = 3f;
|
|
|
|
[SerializeField] private int _health = 2;
|
|
|
|
[SerializeField] private SpriteRenderer _spriteRenderer;
|
|
|
|
[SerializeField] private float _blinkDuration = 0.2f;
|
|
[SerializeField] private Color _hitColor = Color.red;
|
|
|
|
[SerializeField] private AudioSource _audioSource;
|
|
|
|
private Color _originalColor;
|
|
|
|
private Vector3 _startPosition;
|
|
private bool _facingRight = true;
|
|
|
|
private AudioClip _deathClip;
|
|
|
|
private void Start()
|
|
{
|
|
_deathClip = Resources.Load<AudioClip>("Audio/SFX/BirdDeathSFX");
|
|
_startPosition = transform.position;
|
|
}
|
|
|
|
private void Update()
|
|
{
|
|
Patrol();
|
|
}
|
|
|
|
private void Patrol()
|
|
{
|
|
var targetX = _facingRight
|
|
? _startPosition.x + _patrolDistance
|
|
: _startPosition.x - _patrolDistance;
|
|
|
|
transform.position = Vector3.MoveTowards(
|
|
transform.position,
|
|
new Vector3(targetX, transform.position.y, transform.position.z),
|
|
_speed * Time.deltaTime
|
|
);
|
|
|
|
if (Mathf.Approximately(transform.position.x, targetX))
|
|
{
|
|
Flip();
|
|
}
|
|
}
|
|
|
|
private void Flip()
|
|
{
|
|
_facingRight = !_facingRight;
|
|
transform.localScale = new Vector3(
|
|
-transform.localScale.x,
|
|
transform.localScale.y,
|
|
transform.localScale.z
|
|
);
|
|
}
|
|
|
|
private void OnTriggerEnter2D(Collider2D other)
|
|
{
|
|
if (!other.CompareTag("Player")) return;
|
|
|
|
var playerHealth = other.GetComponent<PlayerHealth>();
|
|
playerHealth?.TakeDamage();
|
|
}
|
|
|
|
public void TakeDamage()
|
|
{
|
|
_health--;
|
|
BlinkHit();
|
|
if (_health <= 0)
|
|
{
|
|
Die();
|
|
}
|
|
}
|
|
|
|
private void BlinkHit()
|
|
{
|
|
var originalColor = _spriteRenderer.color;
|
|
var hitColor = new Color(_hitColor.r, _hitColor.g, _hitColor.b, originalColor.a);
|
|
|
|
DOTween.Sequence()
|
|
.Append(_spriteRenderer.DOColor(hitColor, _blinkDuration / 4))
|
|
.Append(_spriteRenderer.DOColor(originalColor, _blinkDuration / 4))
|
|
.Append(_spriteRenderer.DOColor(hitColor, _blinkDuration / 4))
|
|
.Append(_spriteRenderer.DOColor(originalColor, _blinkDuration / 4))
|
|
.SetEase(Ease.Linear)
|
|
.SetLink(gameObject);
|
|
}
|
|
|
|
private void Die()
|
|
{
|
|
_audioSource.PlayOneShot(_deathClip);
|
|
Destroy(gameObject);
|
|
}
|
|
}
|
|
} |