将自定义AABB分配给游戏对象

时间:2019-05-11 14:41:33

标签: c#

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

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

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

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脚本。我想做的就是将truefalse打印到控制台上(如果它们不冲突)。 我很确定aabb已“附加?”到一个游戏对象,这样做(aabb,aabb)只会返回true,我没有这样做。 如果它们碰撞,则将TRUE打印到控制台;如果它们没有碰撞,则将FALSE打印到控制台。

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

0 个答案:

没有答案
相关问题