UNITY

[Unity] 2D Content 제작하기 (4) (OnCollisionEnter2D)

연듀 2022. 4. 25. 17:21

 

물체 충돌 검사 하기

 

 

add Tag를 해 ChickBall 태그를 추가한 후 적용시킨다. 

Item도 마찬가지로 태그를 추가한다. 

 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class cshCannonBall : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {

    }

    private void OnCollisionEnter2D(Collision2D collision) // collision: 충돌된 물체
    {
        if (collision.gameObject.tag == "ChickBall" || collision.gameObject.tag == "Item")
            // 충돌된 object가 가지고 있는 태그가 ChickBall 또는 Item 이라면 
        {
            Destroy(collision.gameObject); // 충돌된 object를 destroy
            Destroy(gameObject); // 자기 자신도 destroy 
        }
    }
}

 

cannonBall에 이 스크립트를 추가한다. 

 

cannonBall이 태그가 ChickBall, Item인 오브젝트와 충돌하면 오브젝트와 cannonBall이 둘다 사라지게 된다.