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
'프로그래밍 > Unity' 카테고리의 다른 글
[Unity] 물리를 이용한 오브젝트 이동(속력, 힘, 회전) (1) | 2022.03.28 |
---|---|
[Unity] Mesh, Material, Collider, RigidBody (0) | 2022.03.27 |
[Unity] 오브젝트 이동 (3) | 2022.03.22 |
[Unity] 키 입력 anyKey, GetKey, GetMouseButton, GetButton (0) | 2022.03.21 |
[Unity] 유니티 입문 / 유니티 흐름, 라이프사이클 (0) | 2022.03.20 |
댓글