unity判断点是否在长方体内部

using UnityEngine;

public class CubeCheck : MonoBehaviour
{
    // 长方体的位置、旋转和尺寸
    public Vector3 position = new Vector3(0, 0, 0);
    public Quaternion rotation = Quaternion.identity;
    public Vector3 size = new Vector3(1, 1, 1);

    public Transform check;//需要检测的物体
    public bool isIn;
    
    // 长方体对象
    private Bounds cubeBounds;

    void Start()
    {
        // 创建长方体对象
        cubeBounds = new Bounds(position, size);
    }

    void Update() 
    {
        position = transform.position;
        rotation = transform.rotation;
        
        // 检查点是否在长方体内部
        Vector3 pointToCheck = check.position; // 替换为要检查的点的坐标

        // 逆旋转点
        Vector3 localPoint = Quaternion.Inverse(rotation) * (pointToCheck - position);

        // 检查逆旋转后的点是否在长方体内部
        bool isInside = cubeBounds.Contains(localPoint);

        // 输出结果
        if (isInside)
        {
            Debug.Log("点在长方体内部");
        }
        else
        {
            Debug.Log("点在长方体外部");
        }

        isIn = isInside;
    }
}

 

posted @ 2023-12-11 18:27  三页菌  阅读(74)  评论(0编辑  收藏  举报