유니티(unity) 오브젝트 파괴/파편 (Collider/Rigidbody 이용)2편

1편에서 GetComponentsInChildren 을 이용해서 자식 오브젝트들의 컴퍼넌트에 접근했습니다.

파괴되는 오브젝트 종류가 물통 한 종류도 아니고, 여러개의 또는 몇 십개의 파괴 오브젝트에 "Box Collider", "Rigidbody"를 수동으로 컴퍼넌트 추가를 하려니 이것도 비효율적입니다.

스크립트를 이용해서 자식 오브젝트에 컴퍼넌트를 추가할 수 있습니다.

아래 c# 스크립트입니다.
using UnityEngine;
using System.Collections;

public class addcomp : MonoBehaviour {

public Component[] component;

public Collider[] colliders;

public float Mass = 1;

public float Drag = 2;

void Awake() {

component = gameObject.GetComponentsInChildren<Comp/onent>();//컴포넌트 사이 "/" 제거하십쇼
foreach(Component item in component)

{
item.gameObject.AddComponent<Box/Collider>(); //박스 콜라이더 사이 "/" 제거 하십쇼
item.gameObject.AddComponent<Rigid/body>(); //리자드 바디 사이 "/"제거 하십쇼
item.rigidbody.constraints = (RigidbodyConstraints)126;

item.rigidbody.mass = Mass;

item.rigidbody.drag = Drag;

}

              }

             

               void OnTriggerEnter(Collider col)
              {
                  if(col.tag == "Weapon")
                   {
                        colliders = gameObject.GetComponentsInChildren<Collider>();
                        foreach(Collider item in colliders)
                        {  
                         item.rigidbody.constraints = (RigidbodyConstraints)0;
                         Destroy(gameObject, 10);
                        }
                   }

             }

}

1부에서 봤던 스크립트와 거의 비슷합니다.

Collider[] -> Component[]

collider -> component

위와같이 단어만 바꿔주면 됩니다.(대소문자 주의!)

유니티가 실행이되면 컴퍼넌트가 추가 되지 않기 때문에 void Awake() 에서 컴퍼넌트를 추가 합니다.

컴퍼넌트를 추가 할때는 gameObject.AddComponent<해당 컴퍼넌트 이름>(); 을 사용합니다.

item.gameObject.AddComponent<Box/Collider>();//박스 콜라이더 사이 "/" 제거 하십쇼
item.gameObject.AddComponent<Rigid/body>(); // 리자드 바디 사이 "/"제거 하십쇼

item.gameObject.AddComponent<해당 컴퍼넌트 이름>(); // 이와같이 해당 컴퍼넌트 이름을 입력해주면 됩니다.

rigidbody.constraints = RigidbodyConstraints.FreezeRotationX

파괴 오브젝트 스크립트의 핵심은 Rigidbody의 Constraints의 Freeze를 조절 하는것입니다.

   Freeze None 없음 = 0,
   FreezePositionX = 2,
   FreezePositionY = 4,
   FreezePositionZ = 8,
   FreezePosition = 14, //Position체크 전부 체크
   FreezeRotationX = 16,
   FreezeRotationY = 32,
   FreezeRotationZ = 64,
   FreezeRotation = 112, //Rotation만  전부 체크
   FreezeAll = 126 ,

item.rigidbody.constraints = (RigidbodyConstraints)126; //Freeze Position, Rotation 전부 체크
item.rigidbody.constraints = (RigidbodyConstraints)0; //Freeze Position, Rotation 전부 체크 해제

Freeze 값을 적절하게 이용해주면 사방으로 튀는 파괴오브젝트뿐만 아니라 무너져 내리는 벽도 응용할 수 있습니다.

무너져 내리는 벽을 상,중,하로 나누고, 하단에 파편 오브젝트는 XYZ 전부 튀게 해주고

상,중단에 있는 파편 오브젝트에는 X,Z축만 Freeze를 걸어주면 상,중단 파편 오브젝트는 아래쪽으로 스스륵 무너집니다.

Coin Marketplace

STEEM 0.28
TRX 0.12
JST 0.032
BTC 66912.93
ETH 3115.60
USDT 1.00
SBD 3.78