C# simple 3D Collision detection

夙愿已清 提交于 2019-12-06 09:47:35

问题


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 full 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


回答1:


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!



来源:https://stackoverflow.com/questions/5558088/c-sharp-simple-3d-collision-detection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!