unity立方体和球体相交
2022-04-29 本文已影响0人
好怕怕
image.png
image.png image.png
image.png
image.png image.png
image.png
using UnityEngine;
public class CubeShphereAABB : MonoBehaviour
{
public Transform cube;
public Transform sphere;
public Vector3 cubeMin;
public Vector3 cubeMax;
public Vector3 sphereCenter;
public float sphereRadius;
[ContextMenu("A")]
public void Awake()
{
var center = cube.position;
var size = cube.localScale;
var xo = size.x / 2;
var yo = size.y / 2;
var zo = size.z / 2;
cubeMin.x = center.x - xo;
cubeMin.y = center.y - yo;
cubeMin.z = center.z - zo;
cubeMax.x = center.x + xo;
cubeMax.y = center.y + yo;
cubeMax.z = center.z + zo;
sphereRadius = sphere.localScale.x / 2;
}
void Update()
{
bool collider = AABB();
sphere.GetComponent<MeshRenderer>().material.color = collider ? Color.red : Color.green;
Debug.LogError(collider);
}
public bool AABB()
{
sphereCenter = sphere.position;
Vector3 point = sphereCenter;
point.x = point.x > cubeMax.x ? cubeMax.x : point.x;
point.x = point.x < cubeMin.x ? cubeMin.x : point.x;
point.y = point.y > cubeMax.y ? cubeMax.y : point.y;
point.y = point.y < cubeMin.y ? cubeMin.y : point.y;
point.z = point.z > cubeMax.z ? cubeMax.z : point.z;
point.z = point.z < cubeMin.z ? cubeMin.z : point.z;
var dis = Vector3.Distance(point, sphereCenter);
return dis <= sphereRadius;
}
}