59 lines
1.5 KiB
C#
59 lines
1.5 KiB
C#
using UnityEngine;
|
|
|
|
public class EnemyMove : MonoBehaviour
|
|
{
|
|
Rigidbody2D _rigidbody;
|
|
SpriteRenderer _spriteRenderer;
|
|
|
|
// 변수
|
|
[SerializeField]
|
|
public int hp = 3;
|
|
|
|
void Awake()
|
|
{
|
|
_rigidbody = GetComponent<Rigidbody2D>();
|
|
_spriteRenderer = GetComponentInChildren<SpriteRenderer>(); // 자식 오브젝트에 스프라이트 랜더러를 불러올때는 InChildren 사용
|
|
}
|
|
|
|
private void FixedUpdate()
|
|
{
|
|
_rigidbody.linearVelocity = new Vector2(-1, _rigidbody.linearVelocityX);
|
|
}
|
|
|
|
// 공격 판정 콜라이더에 닿았을 때 호출
|
|
void OnTriggerEnter2D(Collider2D other)
|
|
{
|
|
if (other.gameObject.layer == LayerMask.NameToLayer("PlayerAttack"))
|
|
{
|
|
OnDamaged(other.transform.position);
|
|
}
|
|
}
|
|
|
|
// 데미지 처리 메서드
|
|
public void OnDamaged(Vector2 playerPosition)
|
|
{
|
|
hp--; // 체력 감소
|
|
|
|
// 피격 시 잠시 정지
|
|
_rigidbody.linearVelocity = Vector2.zero;
|
|
|
|
// 반투명 효과 적용
|
|
_spriteRenderer.color = new Color(1, 1, 1, 0.5f);
|
|
|
|
// 일정 시간 후 원래 색상으로 돌아오는 Invoke 호출
|
|
Invoke("OffDamaged", 1f);
|
|
|
|
// 체력이 0 이하가 되면 파괴
|
|
if (hp <= 0)
|
|
{
|
|
Destroy(gameObject);
|
|
}
|
|
}
|
|
|
|
// 반투명 효과를 없애고 원래 색상으로 되돌리는 메서드
|
|
void OffDamaged()
|
|
{
|
|
_spriteRenderer.color = new Color(1, 1, 1, 1f);
|
|
}
|
|
}
|