Search code examples
c++collision-detection

I have roads stored as an array of rectangles, How to detect collision between car and the roads


The roads don't have any elevation, the y coordinate is 0. The car is 3d, but for collision detection it can be taken as 2d rectangle.

My structure :

struct rectangle
{
    // 4 coordinates of the rectangle
    float x1_left, y1_left;
    float x1_right, y1_right;

    float x2_left, y2_left;
    float x2_right, y2_right;

    double thetaSlope;
};

I have array of all these rectangles that make up the road, initially car is inside the first rectangle.

I searched collision detection and found - simple 2d collision detection between 2 rectangles, but how to determine if my car lies in a particular rectangle, also car should be able to move from one rectangle to other easily, but not come out of the sides of the rectangle.

I am looking for an fairly simple solution.The roads top view


Solution

  • Create Point2d class and define rectangle as container of points. For example:

        struct rectangle
        {
            Point2d p1;
            Point2d p2;
            Point2d p3;
            Point2d p4;
    
            double thetaSlope;
        };
    

    or

        struct rectangle
        {
            Point2d points[4];
    
            double thetaSlope;
        };
    

    With this abstraction code is simpler.

    You should mark sides of rectangles as penetrable or not penetrable. In collision detection take part only not penetrable sides.

    I think using polygons instead of rectangles is simpler solution. You can define whole map as one big polygon and do not treat movement from one rectangle to another.