首页 > 解决方案 > 将自定义 AABB 分配给游戏对象

问题描述

我正在尝试在我的 Unity 项目中设置自定义数学代码,以使用 AABB 测试碰撞。

到目前为止,我很确定我的代码只是用来计算两个盒子是否发生碰撞,但不确定我如何将它们附加到游戏对象以测试它们是否发生碰撞。

这是我目前拥有的代码。LineIntersection我相信andIntersectingAxis函数可以忽略,它只是我课程的一部分。

public class AABB
    {
        public AABB(Vector3 Min, Vector3 Max)
        {
            MinExtent = Min;
            MaxExtent = Max;
        }

        //This could be a Vector2 if you want to do 2D Bounding Boxes
        Vector3 MinExtent;
        Vector3 MaxExtent;

        public float Top
        {
            get { return MaxExtent.y; }
        }

        public float Bottom
        {
            get { return MinExtent.y; }
        }

        public float Left
        {
            get { return MinExtent.x; }
        }

        public float Right
        {
            get { return MaxExtent.x; }
        }

        public float Front
        {
            get { return MaxExtent.z; }
        }

        public float Back
        {
            get { return MinExtent.z; }
        }

        public static bool Intersects(AABB Box1, AABB Box2)
        {
            return !(Box2.Left > Box1.Right
                || Box2.Right < Box1.Left
                || Box2.Top < Box1.Bottom
                || Box2.Bottom > Box1.Top
                || Box2.Back > Box1.Front
                || Box2.Front < Box1.Back);


        }


    }

在另一个名为我的脚本中,AABBCollider我有以下代码

[RequireComponent(typeof(MatrixController))]
public class AABBCollider : MonoBehaviour {

    private MatrixController MCCache;
    public Vector3 CubeSize = new Vector3(1,1,1);

    public VectorAlgorithm.AABB aabb;
    public VectorAlgorithm.AABB aabb2;
    //public VectorAlgorithm.AABB other;

    public bool Intersect(AABBCollider other)
    {
        return VectorAlgorithm.AABB.Intersects(aabb, other.aabb);
    }

    // Use this for initialization
    void Start () {
       MCCache = GetComponent<MatrixController>();
       //aabb = new VectorAlgorithm.AABB(MCCache.position - CubeSize, MCCache.position + CubeSize);
    }

    // Update is called once per frame
    void Update () {
        aabb = new VectorAlgorithm.AABB(MCCache.position - CubeSize, MCCache.position + CubeSize);
        Debug.Log(VectorAlgorithm.AABB.Intersects(aabb, aabb));
    }
}

它附加到我的“PlayerCharacter”和“Enemy”游戏对象的 AABBCollider 脚本。我要做的就是打印到控制台,true或者false它们是否发生碰撞。我很确定 aabb 是“附加的???” 到一个游戏对象,所以这样做 (aabb, aabb) 只会返回 true,我不在乎。如果他们碰撞,打印TRUE到控制台,如果他们没有碰撞,打印FALSE到控制台。

在这个阶段,我不太担心如果它们发生碰撞会将它们分开,只是想知道我的功能是否正常工作。

标签: c#

解决方案


推荐阅读