학습 주제

빗방울 오브젝트를 생성하고 바닥과 충돌 시 사라지게 만들기

학습 목표는 무엇입니까?

오브젝트 충돌 관리와 충돌 시 제거 구현

학습 내용

학습 내용을 작성해주세요

  • 중력을 작동시켜 아래로 떨어지게 하는 물리엔진은 Rigidbody(현재 프로젝트는 2D 사용)
  • 충돌 이벤트를 만들기 위해서는 충돌과 관련된 오브젝트에 collider 컴포넌트를 추가한다
    • ground는 box collider 2d 사용
    • rain은 circle collider 2d 사용
  • 부딪히는 순간 오브젝트를 추적하고 제거하려면 스크립트에서 private void OnCollisionEnter2D(Collision2D collision) 함수를 이용
    • 함수 내에서 만약 충돌한 오브젝트가 ground라면~ 으로 분기를 만들기
      • 이 Ground를 gameObject.name 속성으로 넣는다면 이름이 바뀌면 트래킹 불가
      • 그래서 Ground라는 에셋 태그를 만들어 추가하는 방식으로 해소
    • 값이 ground라면, rain 스크립트 컴포넌트를 파괴하는 명령어를 작성하기

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

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

    }

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

    }

    private void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.CompareTag("Ground"))
        {
            Destroy(this.gameObject);
        }
    }
}

 

+ Recent posts