Sphere끼리 충돌 구현 실험.
간단하게 실험을 하기 위해 두 개의 구만 충돌이 일어나게 하였다.
닿았을 때
구의 충돌은 구하기 쉽다. 두 점 사이의 거리가 양쪽 구의 반지름들을 더한 값보다 작으면 충돌했다고 판정된다.
아래는 소스코드.
만드는김에 제곱근, 제곱, 두 점 사이의 거리를 구해주는 함수도 직접 만들어봄.
public class CSphereCollider : MonoBehaviour
{
public Vector3 pivotPos;
public float radius; // 반지름
public GameObject otherSphere;
private Vector3 otherPivotPos;
private float otherRadius; // 상대방 반지름
// Update is called once per frame
void Update()
{
transform.localScale = new Vector3(radius*2, radius*2, radius*2);
pivotPos = gameObject.transform.position;
Vector3 otherPivotPos = otherSphere.gameObject.transform.position;
otherRadius = otherSphere.gameObject.GetComponent<CSphereCollider>().radius;
CheckCollider(pivotPos, otherPivotPos);
}
public void CheckCollider(Vector3 pos1, Vector3 pos2)
{
float distance = GetDistance(pos1, pos2);
// 충돌이 일어났다.
if (distance < radius + otherRadius)
{
Debug.Log("충돌이 일어남");
}
}
// 유클리드 거리, 두 점 사이의 거리를 구한다.
public float GetDistance(Vector3 currentPos, Vector3 targetPos)
{
float distance;
float _x = targetPos.x - currentPos.x;
float _y = targetPos.y - currentPos.y;
float _z = targetPos.z - currentPos.z;
distance = GetSQRT(GetPow(_x, 2) + GetPow(_y, 2) + GetPow(_z, 2));
return distance;
}
/// <summary>
/// 제곱을 구해준다.
/// </summary>
/// <param name="number">숫자</param>
/// <param name="n">지수</param>
/// <returns>제곱된 수</returns>
public float GetPow(float number, int n)
{
float value = 1;
for(int i=0;i < n; ++i)
{
value *= number;
}
return value;
}
// 제곱근을 구해준다.
public float GetSQRT(float value)
{
// 바빌로니아 법을 이용한다.
float x = 3; // 임의의 값.
// 정확도가 높아질때까지 반복
for(int i =0;i < 10; ++i)
{
x = (x + (value / x)) / 2;
}
return x;
}
private void OnDrawGizmos()
{
Gizmos.DrawWireSphere(pivotPos, radius);
}
}
'게임 개발 > 유니티' 카테고리의 다른 글
유니티에서 2D로 되어있는 버텍스 정보를 이용한 3D 변환 (0) | 2020.04.03 |
---|---|
Unity 2D 길찾기 알고리즘 구현 (0) | 2020.01.14 |
Unity로 원형 선 그리기 (0) | 2020.01.01 |
Unity로 CubeCollider 만들기 -제작중- (0) | 2020.01.01 |
Unity로 Cube 만들기 (0) | 2020.01.01 |