본문 바로가기
프로그래밍/Unity

[Unity] 충돌 이벤트

by 정빈e 2022. 3. 29.
728x90

실행화면

적용코드

MyBall.cs

public class MyBall : MonoBehaviour
{
    Rigidbody rigid;

    void Start()
    {
        rigid = GetComponent<Rigidbody>();
    }


    void FixedUpdate()
    {
        float h = Input.GetAxisRaw("Horizontal");
        float v = Input.GetAxisRaw("Vertical");

        Vector3 vec = new Vector3(h, 0, v);

        rigid.AddForce(vec, ForceMode.Impulse); 

    }

    private void OnTriggerStay(Collider other)
    {
        if (other.name == "Cube")
            rigid.AddForce(Vector3.up * 2, ForceMode.Impulse);
    }
}

 

OtherBall.cs

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

public class OtherBall : MonoBehaviour
{
    MeshRenderer mesh;
    Material mat;

    void Start()
    {
        mesh = GetComponent<MeshRenderer>();
        mat = mesh.material;
    }

	// 오브젝트가 My Ball과 충돌 했을 때 호출
    private void OnCollisionEnter(Collision collision)
    {
        if(collision.gameObject.name == "My Ball")
        { 
            mat.color = new Color(0, 0, 0);
        }
    }

	// 오브젝트가 My Ball과 충돌이 끝났을 때 호출
    private void OnCollisionExit(Collision collision)
    {
        if (collision.gameObject.name == "My Ball")
        {
            mat.color = new Color(1, 1, 1);
        }
    }


}

 

오브젝트의 재질 접근 - MeshRenderer를 통해

 

 

충돌 이벤트

// 실제 물리적인 충돌로 발생하는 이벤트

OnCollisionEnter : 물리적 충돌이 시작할 때 호출되는 함수

OnCollisionStay : 물리적으로 계속 충돌하고 있을 때

OnCollisionExit : 물리적 충돌이 끝날 때 호출되는 함수

private void OnCollisionEnter(Collision collision)
    {

    }

 

// 콜라이더 충돌로 발생하는 이벤트

OnTriggerEnter : 콜라이더 충돌이 시작할 때 호출되는 함수

OnTriggerStay : 콜라이더가 계속 충돌하고 있을 때

OnTriggerExit : 콜라이더 충돌이 끝날 때

private void OnTriggerEnter(Collider other)
    {

    }
728x90

댓글