Unity2D
Unity) [유니티 2D] 플레이어 피격 구현
HSH12345
2023. 4. 26. 15:34
void FixedUpdate()
{
if (this.playerHP >= 0)
{
Collider2D[] colliders = Physics2D.OverlapBoxAll(this.player.transform.position, new Vector2(0.5f, 0.5f), 0);
foreach (Collider2D collider in colliders)
{
if (collider.CompareTag("Monster") || collider.CompareTag("MonsterBullet"))
{
if (!this.isHitting && this.playerHP > 0)
{
StartCoroutine(this.PlayerDamagedRoutine());
}
}
if (collider.CompareTag("Food") && this.playerHP < 3 && this.playerHP > 0)
{
Destroy(collider.gameObject);
this.playerHP++;
if (this.playerHP == 3) this.director.healthDirector.healthGOs[2].SetActive(true);
else if (this.playerHP == 2) this.director.healthDirector.healthGOs[1].SetActive(true);
}
}
}
}
IEnumerator PlayerDamagedRoutine()
{
this.isHitting = true;
this.playerHP--;
Debug.LogFormat("HP : {0}", this.playerHP);
EventDispatcher.Instance.Dispatch(EventDispatcher.EventName.CoCameraShakingAndFlash);
if (this.playerHP == 2) this.director.healthDirector.healthGOs[2].SetActive(false);
else if (this.playerHP == 1) this.director.healthDirector.healthGOs[1].SetActive(false);
else if (this.playerHP == 0) this.director.healthDirector.healthGOs[0].SetActive(false);
if (this.playerHP <= 0)
{
var playerShell = this.player.GetComponent<PlayerShell>();
playerShell.rBody2d.simulated = false;
playerShell.anim.SetInteger("State", -1);
playerShell.anim.Play("Dead", -1, 0);
playerShell.gunShell.gameObject.SetActive(false);
this.director.gameOverDirector.GameOverAnimStart();
}
yield return new WaitForSeconds(this.damagedTime);
this.isHitting = false;
}
플레이어를 공격할 수 있는 오브젝트의 태그를 검색하여 플레이어가 데미지를 입도록 구현하였습니다.플레이어가 피격될 때마다 죄상단의 체력 UI를 변화시키고 이벤트를 호출하여 카메라 효과를 줍니다. 플레이어가 죽었을 때는 Rigidbody2D를 비활성화하여 플레이어가 더 이상 물리작용하지 않도록 합니다.