Reanimation
Reanimation

Reputation: 3336

C++ Collision using Obj Models

I'm experimenting with OpenGL 3.2+ and have starting loading Obj files/models in 3D and trying to interact with them. (following tutorials from sources like this site)

I was wondering what the easiest way (if it's possible) to set up collision detection between two existing(loaded) Obj objects/Models without using third party physics engines etc?

Upvotes: 2

Views: 3600

Answers (2)

N A
N A

Reputation: 656

Simplest collision model is to use bounding boxes for collision. The principle is simple: You surround your object by a box defined by two points, minimum and maximum. You then use these points to determine whether two boxes intersect.

In my engine the structure of bounding box and collision-detection method are set as this:

typedef struct BoundingBox
{
    Vector3 min; //Contains lowest corner of the box
    Vector3 max; //Contains highest corner of the box
} AABB;

//True if collision is detected, false otherwise
bool detectCollision( BoundingBox a, BoundingBox b )
{
    return (a.min <= b.max && b.min <= a.max);
}

Other simple method is to use spheres. This method is useful for objects that are of similar size in all dimensions but it creates lots of false collisions if they are not. In this method, you surround your object by sphere with radius radius and center position position and when it comes to the collision, you simply check whether the distance between centers is smaller than sum of the radii and that case two spheres intersect.

Again, code snippet from my engine:

struct Sphere
{
    Vector3 position;   //Center of the sphere
    float radius;       //Radius of the sphere
};
bool inf::physics::detectCollision( Sphere a, Sphere b )
{
    Vector3 tmp = a.position - b.position; //Distance between centers
    return (Dot(tmp, tmp) <= pow((a.radius + b.radius), 2));
}

In code above Dot() computes the dot product of two vectors, if you dot vector with itself it gives you (by definition) the magnitude of the vector squared. Notice how I am actually not square-rooting to get the actual distances and I am comparing the squares instead to avoid extra computations.

You should also be aware that neither of these methods are perfect and will give you false collision detection (unless the objects are perfect boxes or spheres) from time to time but that is the trade-off of the simple implementation and computation complexity. Nevertheless it is good way to start detecting collisions.

Upvotes: 0

Netherwire
Netherwire

Reputation: 2787

The easiest possible algorithm that can meet your criteria detects collision between spheres, that concludes your meshes. Here you can see the implementation example.

Upvotes: 1

Related Questions