Programming Language/C#

[C#] Unity 속 C# script(7) : 충돌스크립트

공구일 2024. 12. 10. 19:59
728x90

01. OnCollisionEnter() == Collider과 Rigidbody가 있어야함

-> 충돌이 발생하면 호출되는 메서드를 이용하여 충돌한 두 객체의 이름을 출력 

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

public class Collision_ggi : MonoBehaviour
{
    void OnCollisionEnter(Collision col){
        Debug.Log("나:"+gameObject.name);
        if (col.gameObject.name == "Cylinder")
        	Debug.Log("나와 충돌한 객체:"+col.gameObject.name);
    }
}

- 오브젝트의 이름을 출력하기 위해 name 프로퍼티를 사용하여 출력함

 

-> 충돌시 반대방향으로 튀기기

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

public class Collision_ggi : MonoBehaviour
{
    void OnCollisionEnter(Collision col){
        Vector3 direction = transform.position - col.gameObject.transform.position;
        direction = direction.normalized * 1000; //정규화값에 힘의크기(길이)를 곱해줌
        col.gameObject.GetComponent<Rigidbody>().AddForce(-direction * 0.5f);
    }
}

- Vector3인 direction는 벡터로 충돌한 객체와의 위치를 비교한 뒤 direction에 direction.nomalized를 통해 단위벡터(크기1)로 정규화를 해줌 -> 벡터는 방향과 크기로 나눠지는데 방향만을 나타내고 싶을 때는 direction.nomalized, 크기만을 나타내고 싶을 때는 direction.magnitude를 변수에 대입하면 됨

 

- AddForce(-direction * 0.5f)에서 -direction은 부딪힌 방향의 반대방향으로 힘을 준다는 의미로, 반대방향으로 튕긴 것처럼 보이게 만듦(참고로 두 객체의 위치는 direction = (0,0,5) - (0,0,3))

 

02. OnTriggerEnter() == Collider 속 Is Trigger 속성이 true여야함(활성화 돼있어야함)

- Mesh Renderer 컴포넌트를 제거해주면  시각적으로 보이지 않게 되면서, 그 요소가 렌더링되지 않아 화면에 보이지 않게 됨

- 모든 Collider에 있는 Is Trigger 속성을 true로 바꿔주면(인스펙터 창에서는 체크해주면) 어떤 객체가 영역에 진입했는지에 대한 것ㅇ르 감지하는 이벤트로 충돌이 일어나면 물리적인 반응이 없이 단순 접근을 감지함

-> Cube(넓은 판 모양)를 지나간 객체수와 그 객체의 이름을 출력하는 코드

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

public class Failzone_ggi : MonoBehaviour
{
    int count = 0;
    void OnTriggerEnter(Collision col){
        count++;
        Debug.Log("Fail을 통과한 객체수는"+count);
        Debug.Log(col.gameObject.name);
    }
}

 

-> 공나 실린더가 Fail(넓은 판 모양의 Cube 객체)를 지나가면 게임을 다시 시작함

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

public class Failzone_ggi : MonoBehaviour
{
    void OnTriggerEnter(Collision col){
        Debug.Log(col.gameObject.name);
        if(col.gameObject.name == "Sphere" || col.gameObject.name == "Cylinder")
            SceneManager.LoadScene("col_ggi");
    }
}

- 게임을 다시 시작한다는 것은 게임의 씬을 다시 불러드린다는 것과 같은 의미로 ScenceManager.LoadScene("씬이름")을 통해 다시 scene을 load하도록 만듦 -> 이 SceneManger을 사용하기 위해서는 using UnityEngine.SceneManagement;을 꼭 작성해줘야함

더보기

* 일부 출처 - 고수정, ”게임프로그래밍 ”, 인덕대학교

 

 

 

 

 

 

 

728x90