103 lines
3.2 KiB
C#
103 lines
3.2 KiB
C#
using System;
|
|
using Code.Infrastructure.Audio;
|
|
using Code.Infrastructure.Configs;
|
|
using Cysharp.Threading.Tasks;
|
|
using Reflex.Attributes;
|
|
using UnityEngine;
|
|
|
|
namespace Code.Example.Platformer.Entity.Enemies
|
|
{
|
|
public class Boar : Entity
|
|
{
|
|
[SerializeField] private Vector2 groundLeft;
|
|
[SerializeField] private Vector2 groundRight;
|
|
private bool _directionRight;
|
|
|
|
private float _acceleration = 3f;
|
|
|
|
[SerializeField] private EntityHealth health;
|
|
|
|
[Inject] private IAudioService _audioService;
|
|
|
|
private Transform _target;
|
|
private float _attackThreshold = 0.5f;
|
|
|
|
private void Start()
|
|
{
|
|
health.OnEntityDamage = OnEntityDamage;
|
|
health.OnEntityDeath = OnEntityDeath;
|
|
}
|
|
|
|
private void OnEntityDeath()
|
|
{
|
|
animator.SetBool(Died, true);
|
|
animator.SetTrigger(OnDeath);
|
|
Die().Forget();
|
|
}
|
|
|
|
private async UniTaskVoid Die()
|
|
{
|
|
await UniTask.WaitForSeconds(1);
|
|
_audioService.PlayOneShot(AudioNames.Platformer, 3 , AudioGroupType.SFX);
|
|
Destroy(gameObject);
|
|
}
|
|
private void OnEntityDamage(int obj)
|
|
{
|
|
_audioService.PlayOneShot(AudioNames.Platformer, 2, AudioGroupType.SFX);
|
|
UnityEngine.Debug.Log(gameObject.name + " damaged");
|
|
animator.SetTrigger(OnHit);
|
|
}
|
|
|
|
protected override void Move()
|
|
{
|
|
if (health.IsDead) return;
|
|
if (_target)
|
|
{
|
|
TryAttack();
|
|
_directionRight = (_target.position - transform.position).x > float.Epsilon;
|
|
UnityEngine.Debug.DrawLine(transform.position, (transform.position + (_target.position - transform.position)), Color.salmon);
|
|
|
|
CheckupDirection();
|
|
|
|
rigidbody2D.linearVelocityX = _directionRight ? 0.5f : -0.5f;
|
|
rigidbody2D.linearVelocityX *= _acceleration;
|
|
}
|
|
else
|
|
{
|
|
CheckupDirection();
|
|
|
|
rigidbody2D.linearVelocityX = _directionRight ? 0.5f : -0.5f;
|
|
}
|
|
}
|
|
|
|
protected override void HandleFlipX() => spriteRenderer.flipX = rigidbody2D.linearVelocity.x > -0.01f;
|
|
|
|
private void CheckupDirection()
|
|
{
|
|
if (_directionRight)
|
|
{
|
|
if (!Physics2D.OverlapPoint((Vector2)transform.position + groundRight,
|
|
LayerMasks.Masks[LayerMaskType.PlatformerGround]))
|
|
_directionRight = false;
|
|
}
|
|
else if (!Physics2D.OverlapPoint((Vector2)transform.position + groundLeft,
|
|
LayerMasks.Masks[LayerMaskType.PlatformerGround]))
|
|
_directionRight = true;
|
|
}
|
|
|
|
private void TryAttack()
|
|
{
|
|
if ((transform.position - _target.position).magnitude < _attackThreshold) _target.GetComponent<EntityHealth>().GiveDamage(1);
|
|
}
|
|
|
|
|
|
public void GotTarget(Transform target)
|
|
{
|
|
_target = target;
|
|
}
|
|
public void LostTarget()
|
|
{
|
|
_target = null;
|
|
}
|
|
}
|
|
} |