Unity Bound

Bound:包围盒,边界框,AABB的简称,Mesh,Collider,Renderer都存在bound。(Mesh返回的是自身坐标,其余返回的是世界坐标)。


using UnityEngine;
using System.Collections;
using System.Xml;

public class TestXml : MonoBehaviour {

    public GameObject Target;

    public GameObject Target2;

    Bounds bounds;

    void Start()
    {
        bounds = Target.GetComponent<BoxCollider>().bounds;

        Debug.Log("center:" + bounds.center);//中点
        Debug.Log("Size:" + bounds.size);//bound的大小,等于extents*2
        Debug.Log("Min:" + bounds.min);//bound上最小的点,总是等于center-extents
        Debug.Log("Max:" + bounds.max);//bound上最大的点,总是等于center+extents
        Debug.Log("extents:" + bounds.extents);//圣典上翻译成广度,笔者也不清楚如何理解,它等于size/2

        //传入一个点,找离bounds最近的点,如果点在bounds上,则返回输入的点
        Debug.Log(bounds.ClosestPoint(bounds.center));
        Debug.Log(bounds.ClosestPoint(bounds.min));
        Debug.Log(bounds.ClosestPoint(Vector3.zero));

        //判断点是否在bounds上
        Debug.Log(bounds.Contains(bounds.center));
        Debug.Log(bounds.Contains(bounds.min));
        Debug.Log(bounds.Contains(Vector3.zero));

        Bounds temp = new Bounds(Vector3.zero, Vector3.one * 3);

        bounds.Encapsulate(Vector3.one);//使bound包含这个点

        bounds.Encapsulate(temp);//使bound包含参数bound

        bounds.Expand(Vector3.one * 2);//扩大包围盒

        bounds.SetMinMax(Vector3.zero, Vector3.zero);//设置最大最小点,且比单独设置min,max效率要高

        Debug.Log(bounds.Intersects(temp));//是否与参数包围盒相交

        Debug.Log(bounds.SqrDistance(Vector3.up * 2));//返回一个参数点与bound最近的距离平方;
    }

    bool DetectHit(Ray ray)
    {   
       //判断射线是否在bound上
        return bounds.IntersectRay(ray);
    }

    void Update()
    {
        if (Input.GetMouseButtonDown(0)) {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            if (DetectHit(ray))
            {
                Debug.Log("点中包围盒");
            }
            else {
                Debug.Log("没有点中");
            }
        }
    }
}


转载请注明出处:Mr_Jis的博客

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值