开发者

C# simple 3D Collision detection

I'm trying to develop a simple 3d environment (in openTK, so basically openGL) and implement simple collision detection. I will have the camera object which will have a bounding cube and a world fu开发者_开发技巧ll of triangles and quads.

If I'm given a bounding cube (or bounding sphere if that's easier) and a list of polygons, is there a quick and dirty way to do basic collision detection?

Thanks for any help


Ok, for simple bounding box collision, I wrote the following method that will accept a BoundingBox object and determine if it is inside the the current instance of a BoundingBox.

A bounding box consists of the a Point3D object (same as the Point class but with a Z coordinate) for the center of the bounding box, and the height, width, and depth of the box. With those 4 objects, it calculates the Left (min X), Right (max X), Bottom (min Y), Top (max Y), Front (min Z) and Back (max Z) of the box (The box is axis aligned. This is simple collision). Here is the method to detect if one box is within the other, and if so, modifiy the box to move it outside.

    public void Intersection(ref BoundingBox box)
    {
        double lr = Left - box.Right;
        double rl = box.Left - Right;
        double bt = Bottom - box.Top;
        double tb = box.Bottom - Top;
        double fb = Front - box.Back;
        double bf = box.Front - Back;

        if (lr > 0 || rl > 0 || bt > 0 || tb > 0 || bf > 0 || fb > 0)
            return;

        double max = Math.Max(lr, Math.Max(rl, Math.Max(bt, Math.Max(tb, Math.Max(bf, fb)))));

        if (_complex)
        {
            if (ComplexIntersection(ref box))
                return;
        }

        if (max == lr)
            box.Center.X += max;
        else if (max == rl)
            box.Center.X -= max;
        else if (max == bt)
            box.Center.Y += max;
        else if (max == tb)
            box.Center.Y -= max;
        else if (max == fb)
            box.Center.Z += max;
        else if (max == bf)
            box.Center.Z -= max;
    }

You call it by doing something like: meshData.Box.Intersection(ref camera.box); where meshData is some kind of geometry in the scene and the camera is the object for the current user's perspective.

Hope this is useful for someone else!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜