IDemagable 인터페이스 추가public interface IDamagable
{
void TakePhysicalDamage(int damageAmount);
}
public class PlayerCondition : MonoBehaviour, IDamagable
public event Action onTakeDamage; // 데미지 받을 때 호출할 action
// 데미지 받을 때 필요한 로직 작성 (health 감소, 데미지 Action 호출)
void TakePhysicalDamage(int damageAmount)
{
health.Subtract(damageAmount);
onTakeDamage?.Invoke();
}
캠프파이어 구현하기a. 변수 선언
2.데미지, 2. 데미지 비율
public int damage;
public float damageRate;
b. 데미지를 입는 것들의 리스트를 생성
private List<IDamagable> things = new List<IDamagable>();
c. 리스트에 있는 것들을 데미지만큼 데미지 함수 호출
void DealDamage()
{
// things 리스트에 추가 된 IDamagable 객체의 데미지 함수 호출
for(int i = 0; i<things.Count; i++)
{
things[i].TakePhysicalDamage(damage);
}
}
d. 충돌한 것들을 데미지를 입는 리스트에 넣고, 충돌이 끝나면 그 리스트에서 뺀다.
private void OnTriggerEnter(Collider other)
{
// 충돌된 객체에 IDamagable이 상속되어 있으면 List에 추가
if(other.TryGetComponent(out IDamagable damagable))
{
things.Add(damagable);
}
}
private void OnTriggerExit(Collider other)
{
// Exit 되는 객체에 IDamagable이 상속되어 있으면 List에서 제거
if(other.TryGetComponent(out IDamagable damagable))
{
things.Remove(damagable);
}
}
e.
private void Start()
{
// InvokeRepeating (문자열 메서드 이름 , float 시간 , float 반복 속도 );
InvokeRepeating("DealDamage", 0, damageRate);
}
데미지를 입을 때마다 빨간 이미지가 깜빡이도록 해 보자
a. 캔바스에 빨간 이미지 추가
b. DamageIndicator.cs 생성 후 연결
c. 필요한 변수 선언
public Image image;
public float flashSpeed;
Private Coroutine coroutine;
d. 깜빡일 때 호출될 함수
public void Flash()
{
if (coroutine != null)
{
StopCoroutine(coroutine);
}
image.enabled = true;
image.color = new Color(1f, 105f / 255f, 105f / 255f);
coroutine = StartCoroutine(FadeAway());
}
e. 이미지 알파값 조정 및 코루틴을 활용한 연출
private IEnumerator FadeAway()
{
float startAlpha = 0.3f;
float a = startAlpha;
while(a > 0.0f)
{
a -= (startAlpha / flashSpeed) * Time.deltaTime;
image.color = new Color(1f, 100f / 255f, 100f / 255f, a);
yield return null;
}
image.enabled = false;
}
f. start (onTakeDamage 이벤트에 Flash 함수 추가)
private void Start()
{
CharacterManager.Instance.Player.condition.onTakeDamage += Flash;
}
public event Action onTakeDamage;
onTakeDamage는 이벤트 변수
Action은 매개변수가 없는 메서드를 저장할 수 있는 델리게이트(delegate)
CharacterManager.Instance.Player.condition.onTakeDamage += Flash;
이 이벤트가 발생할 때 Flash 함수가 자동으로 실행된다.
1. 플레이어가 데미지를 입을 때 onTakeDamage 이벤트가 호출됨
2. onTakeDamage에 연결된 함수(Flash)가 실행됨