마리오처럼 몬스터 밟아서 처치하기
Player 스크립트
void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag == "Enemy") {
//Attack
if (rigid.velocity.y < 0 && transform.position.y > collision.transform.position.y)
{
onAttack(collision.transform); //충돌 정보 매개변수로 전달
}
else {
onDamaged(collision.transform.position);
}
}
}
void onAttack(Transform enemy) {
//Reaction Force
rigid.AddForce(Vector2.up * 5, ForceMode2D.Impulse);
//Enemy die
EnemyMove enemyMove = enemy.GetComponent<EnemyMove>();
enemyMove.onDamaged();
}
플레이어와 몬스터가 충돌했을 때,
1. 플레이어가 낙하중인가? 즉, velocity.y가 음수인가?
2. 플레이어의 위치가 충돌물체(몬스터)보다 위인가?
Enemy 스크립트
public void onDamaged()
{
//Sprite Alpha
sprite.color = new Color(1, 1, 1, 0.4f);
//Flip Y
sprite.flipY = true;
//Collider Disable
boxCollider.enabled = false;
//Die Effect Jump
rigid.AddForce(Vector2.up * 5, ForceMode2D.Impulse);
Invoke("deActive", 2);
}
void deActive() {
gameObject.SetActive(false);
}
몬스터가 처치됬을 때의 액션 구현
콜라이더를 비활성화 해서 플랫폼 밑으로 떨어뜨림. 그리고 Invoke함수를 활용해 2초 후 오브젝트를 비활성화
'유니티 2D 기본(Platformer Game)' 카테고리의 다른 글
9. 스테이지 추가 & UI (0) | 2021.12.04 |
---|---|
8. 아이템 먹기 (0) | 2021.12.03 |
6. 플레이어 피격 이벤트 구현 (0) | 2021.11.30 |
5. 몬스터 AI 구현하기 (0) | 2021.11.30 |
4. TileMap으로 플랫폼 만들기 (0) | 2021.11.26 |