SAT Collision detection and response

Hey I managed to implement the serparated axis theorem(SAT), however im finding it very hard to understand how to extract the so called "minimum translation vector" so that the colliding polygons can be separated.

Any advice on how to implement this would be appreciated.

Here's my Collision function:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
struct CollisionInfo
{
    bool collision;
    V2f minVec;
};


CollisionInfo Collision_Entity_SAT(Entity e1, Entity e2)
{
    CollisionInfo result = {};
    
    // get normal of both sides
    V2f normal1 = Normal_V2f(e1.pTop, e1.pRight);
    V2f normal2 = Normal_V2f(e1.pTop, e1.pLeft);
    
    float dp1[4] = {};
    float dp2[4] = {};
    float dp3[4] = {};
    float dp4[4] = {};
  
    // get dotproduct of each entities corner against both normals
    
    dp2[0] = DotProduct_V2f(normal1, e1.pTop);
    dp2[1] = DotProduct_V2f(normal1, e1.pLeft);
    dp2[2] = DotProduct_V2f(normal1, e1.pRight);
    dp2[3] = DotProduct_V2f(normal1, e1.pBottom);
    
    dp1[0] = DotProduct_V2f(normal1, e2.pTop);
    dp1[1] = DotProduct_V2f(normal1, e2.pLeft);
    dp1[2] = DotProduct_V2f(normal1, e2.pRight);
    dp1[3] = DotProduct_V2f(normal1, e2.pBottom);
    
    dp4[0] = DotProduct_V2f(normal2, e1.pTop);
    dp4[1] = DotProduct_V2f(normal2, e1.pLeft);
    dp4[2] = DotProduct_V2f(normal2, e1.pRight);
    dp4[3] = DotProduct_V2f(normal2, e1.pBottom);
    
    dp3[0] = DotProduct_V2f(normal2, e2.pTop);
    dp3[1] = DotProduct_V2f(normal2, e2.pLeft);
    dp3[2] = DotProduct_V2f(normal2, e2.pRight);
    dp3[3] = DotProduct_V2f(normal2, e2.pBottom);
    
    float max_dp1 = Max_f(dp1, sizeof(dp1) / sizeof(float));
    float min_dp1 = Min_f(dp1, sizeof(dp1) / sizeof(float));
    
    float max_dp2 = Max_f(dp2, sizeof(dp2) / sizeof(float));
    float min_dp2 = Min_f(dp2, sizeof(dp2) / sizeof(float));
    
    float max_dp3 = Max_f(dp3, sizeof(dp3) / sizeof(float));
    float min_dp3 = Min_f(dp3, sizeof(dp3) / sizeof(float));
    
    float max_dp4 = Max_f(dp4, sizeof(dp4) / sizeof(float));
    float min_dp4 = Min_f(dp4, sizeof(dp4) / sizeof(float));
    
    V2f minVec = {};
    
    if(max_dp1 > min_dp2 &&
       min_dp1 < max_dp2 &&
       max_dp3 > min_dp4 &&
       min_dp3 < max_dp4)
    {
        result.collision = true;
  
    }
    else
    {
        result.collision = false;

    }
    
    return result;
    
}

Edited by C_Worm on Reason: Initial post
Note: I hesitated to reply to this because its been quite a while since I implemented SAT (or any collision detection/response/physics for that matter) so take this with your favourite amount of salt, its basically an educated guess based on what I remember and can reason out. I happily defer to anybody who is more confident on this topic. Hopefully this helps though :)

When using SAT you have a collection of axes that you're projecting your polygons onto and checking if there are any on which they don't overlap. If they overlap on all axes then the polygons themselves overlap. However as part of this calculation, you already compute (or can easily compute) the *distance* by which they overlap on each axis. The axis with the lowest such distance is the one in which the polygons are conceptually "the closest to being separated".

If you move the polygons apart on that axis then you will have an axis along which they are now separated and therefore can be sure that you have resolved the collision! As to whether this is the *minimum* translation to separate them, I suspect so based on the hand-waving line of reasoning that if you followed this procedure for any axis you could always separate the polygons by moving them some distance but since we picked the axis along which the polygons overlap the least, we know that the distance we need to move them is minimal among all the axes we're checking.

So now we have an axis and a distance to move in order to separate our polygons. You may want to just move one of them the full distance, you may want to move them both half the distance (but in opposite directions). It depends on the objects and the behaviour you're looking for. This is definitely not something I have researched/implemented myself but I believe you tend to run into problems with this sort of thing when you have two or more pairs of objects you're checking for collisions between, where in resolving one intersection you create another (imagine a ball moving into the corner where two walls meet, or getting squashed between two rectangles getting closer together). You'll need some more involved machinery to resolve that with any amount of reliability.

Also note that you're only checking two axes, which is sufficient only if your objects are all axis-aligned rectangles. If you ever rotate anything you'll need to check the other 2 normals as well. :)
Thanks, nice to "hear" your voice on this!
So I've changed the code and now im checking all the axis on both entities however the resolving of the collision works on TWO sides only, when the moving object collides on the "upper" or the "right" side of the other object the moving object just pass through it and instantly ends up on the other side of it.

Im checking a isometric tile against another isometric tile and a simple axis alligned square.


I've also tested all my vector/math functions and the seem to work.

I'll paste the SAT function and the place in the code where i use it :)


SAT_Function()

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
CollisionInfo Collision_Entity_SAT(Entity e1, Entity e2)
{
    CollisionInfo result = {};
    
    float dot_e1[4] = {};
    float dot_e2[4] = {};
    
    V2f normals_e1[4] = {};
    V2f normals_e2[4] = {};
    V2f mtv = {};
    
    float minDot_e1 = 0.0f;
    float maxDot_e1 = 0.0f;
    
    float minDot_e2 = 0.0f;
    float maxDot_e2 = 0.0f;
    
    float overlap = 100000000.0f;
    float tempOverlap = 0.0f;
    
    // Get normals_e1 of all sides and make them unit vectors
    for(i32 i = 0; i < 4; i++)
    {
        
        if(i == 3)
        {
            normals_e1[i] = Unit_V2f(Normal_V2f(e1.points[i], e1.points[(i - 3)]));
            
        }
        else
        {
            normals_e1[i] = Unit_V2f(Normal_V2f(e1.points[i], e1.points[(i + 1)]));
            
        }
        
    }
    
    // Get normals_e2 of all sides and make them unit vectors
    for(i32 i = 0; i < 4; i++)
    {
        
        if(i == 3)
        {
            normals_e2[i] = Unit_V2f(Normal_V2f(e2.points[i], e2.points[(i - 3)]));
            
        }
        else
        {
            normals_e2[i] = Unit_V2f(Normal_V2f(e2.points[i], e2.points[(i + 1)]));
            
        }
        
    }
    
    
    
    for(i32 j = 0, i = 0; j < 4; j++)
    {
        
        for(i = 0; i < 4; i++)
        {
            
            // calc dot products of all points one normal at a time
            dot_e1[i] = DotProduct_V2f(normals_e1[j], e1.points[i]);
            dot_e2[i] = DotProduct_V2f(normals_e1[j], e2.points[i]);
            
        }
        
        // Get min/max Dotproducts of each entity against 1 normal at a time
        minDot_e1 = Min_f(dot_e1, sizeof(dot_e1)/sizeof(float));
        maxDot_e1 = Max_f(dot_e1, sizeof(dot_e1)/sizeof(float));
        
        minDot_e2 = Min_f(dot_e2, sizeof(dot_e2)/sizeof(float));
        maxDot_e2 = Max_f(dot_e2, sizeof(dot_e2)/sizeof(float));
        
        // Check for overlapp
        tempOverlap = OverLap(minDot_e1, maxDot_e1, minDot_e2, maxDot_e2);
        
        // No overlapp = no collision
        if(tempOverlap <= 0.0f)
        {
            
            result.collision = false;
            result.mtv = v2f(0.0f, 0.0f);
            result.minPenetration = 0.0f;
            return result;
        }
        // some overlapp occured = collision on the axis currently under control
        else
        {
            
            if(tempOverlap < overlap)
            {
                overlap = tempOverlap;
                mtv = normals_e1[j];
                result.minPenetration = overlap;
            }
            
        }
        
    }
    
    
    // Do it all again but check against the normals on the other entity
    for(i32 j = 0, i = 0; j < 4; j++)
    {
        
        for(i = 0; i < 4; i++)
        {
            
            // calc dot products of all points one normal at a time
            dot_e1[i] = DotProduct_V2f(normals_e2[j], e1.points[i]);
            dot_e2[i] = DotProduct_V2f(normals_e2[j], e2.points[i]);
            
        }
        
        // get min/max DP's
        minDot_e1 = Min_f(dot_e1, sizeof(dot_e1)/sizeof(float));
        maxDot_e1 = Max_f(dot_e1, sizeof(dot_e1)/sizeof(float));
        
        minDot_e2 = Min_f(dot_e2, sizeof(dot_e2)/sizeof(float));
        maxDot_e2 = Max_f(dot_e2, sizeof(dot_e2)/sizeof(float));
        
        // Check for overlapp
        tempOverlap = OverLap(minDot_e1, maxDot_e1, minDot_e2, maxDot_e2);
        if(tempOverlap <= 0.0f)
        {
            
            result.collision = false;
            result.mtv = v2f(0.0f, 0.0f);
            result.minPenetration = 0.0f;
            return result;
        }
        else
        {
            
            if(tempOverlap < overlap)
            {
                
                overlap = tempOverlap;
                mtv = normals_e2[j];
                result.minPenetration = overlap;
                
            }
            
        }
        
    }
    
    // Collision occured and we obtain the minimum penetration magnitude and the corresponding axis
    result.mtv = Scalar_V2f(result.minPenetration, mtv);
    result.collision = true;
    
    return result;
    
}





where I use it

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
    CollisionInfo ci_0 = {};
    CollisionInfo ci_1 = {};
    // COLLISION CHECKING
    
    ci_1 = Collision_Entity_SAT(e[tile_00], e[tile_00 + 1]);
    ci_0 = Collision_Entity_SAT(e[tile_00], e[ghostSorc]);
    
    if(ci_1.collision || ci_0.collision)
    {
        if(ci_1.collision)
        {
            printf("c_1.overlap: %f\n", ci_1.minPenetration);
            printf("c_1.mtv: ( %f, %f )\n\n", ci_1.mtv.x, ci_1.mtv.y);
            
           
            e[tile_00].SetSolidColor(0.0f, 0.5f, 0.0f, 1.0f);
            e[tile_00].Move(ci_1.mtv);
            
        }
        
        if(ci_0.collision)
        {
            printf("c_0.overlap: %f\n", ci_0.minPenetration);
            printf("c_0.mtv: ( %f, %f )\n\n", ci_0.mtv.x, ci_0.mtv.y);
            
            
            e[tile_00].SetSolidColor(0.0f, 0.5f, 0.0f, 1.0f);
            e[tile_00].Move(ci_0.mtv);
        }
    }
    else
    {
        e[tile_00].SetSolidColor(0.2f, 0.0f, 0.2f, 1.0f);
    }
    

Edited by C_Worm on
What does the OverLap function does (what is the code) ?

Have you tried stepping in the code to see what is breaking ?

Have you tried drawing the axis, the projections and the result to see if they look correct ?

Edited by Simon Anciaux on
Yes i've stepped in and looked at it and from what i can see the axis are correct.

The projections (Dot products) also seems right.


.... been working on this collision-system for like atleast 2 weeks now xD


Overlap():
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
float OverLap(float min1, float max1, float min2, float max2)
{
    float min = 0.0f;
    float max = 0.0f;
    float overlap = 0.0f;
    
    if(max1 < max2)
    {
        max = max1;
    }
    else
    {
        max = max2;
    }
    
    if(min1 < min2)
    {
        min = min2;
    }
    else
    {
        min = min1;
    }
    
    overlap = max - min;
    
    return overlap;
}
I did a small test out of curiosity, and it seems that the result of my code (which I think should be similar to yours) sometimes gives a result meant to move shape A and other times to move shape B. That means, that the code gives the minimum amount you have to move, and the axis, but not the direction.

I fixed it by comparing minDot_e1 and minDot_e2 and returning a negative direction (relative to the axis) if minDot_e1 < minDot_e2. Meaning the vector to move a in sat( a, b ) is axis * magnitude * direction. I think it should do it but I didn't test much as my "setup" is no practical to do so.

The following code will produce a series of images, with the two shapes in white, and a red line indicating in which direction moving the first shape to solve the collision (the first shape is the one not moving, at the center). You can play with the values to test different shapes, movements...

If you comment
1
2
3
if ( a_min < b_min ) {
    result.direction = -1;
}

you can see the incorrect result when shape B has nearly exited shape A to the bottom left (the red arrow is in the wrong direction).

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
#include <stdio.h>
#include <math.h>

typedef float r32;
typedef unsigned int u32;

typedef struct vec2_t {
    r32 x, y;
} vec2_t;

r32 v2_dot( vec2_t a, vec2_t b ) {
    r32 result = a.x * b.x + a.y * b.y;
    return result;
}

vec2_t v2_perp( vec2_t a ) {
    vec2_t result;
    result.x = -a.y;
    result.y = a.x;
    return result;
}

vec2_t v2_normalized( vec2_t a ) {
    
    r32 length = sqrtf( a.x * a.x + a.y * a.y );
    a.x = a.x / length;
    a.y = a.y / length;
    
    return a;
}

#define min( a, b ) ( ( ( a ) < ( b ) ) ? ( a ) : ( b ) )
#define max( a, b ) ( ( ( a ) > ( b ) ) ? ( a ) : ( b ) )
#define swap( a, b, type ) { type __backup__ = ( a ); ( a ) = ( b ); ( b ) = __backup__; }

typedef struct sat_result_t {
    vec2_t axis;
    r32 magnitude;
    r32 direction;
} sat_result_t;

sat_result_t sat( vec2_t* a, vec2_t* b ) {
    
    sat_result_t result = { 0 };
    result.magnitude = 1000000.0f;
    
    int stop = 0;
    
    vec2_t axis[ 8 ];
    
    for ( int i = 0; i < 4; i++ ) {
        vec2_t va = { a[ i + 1 ].x - a[ i ].x, a[ i + 1 ].y - a[ i ].y };
        vec2_t vb = { b[ i + 1 ].x - b[ i ].x, b[ i + 1 ].y - b[ i ].y };
        axis[ i ] = v2_normalized( v2_perp( va ) );
        axis[ 4 + i ] = v2_normalized( v2_perp( vb ) );
    }
    
    for ( int axis_index = 0; axis_index < 8; axis_index++ ) {
        
        r32 a_min = 1000000.0f;
        r32 a_max = -a_min;
        
        r32 b_min = 1000000.0f;
        r32 b_max = -b_min;
        
        for ( int point_index = 0; point_index < 4; point_index++ ) {
            
            r32 a_dot = v2_dot( axis[ axis_index ], a[ point_index ] );
            r32 b_dot = v2_dot( axis[ axis_index ], b[ point_index ] );
            
            a_min = min( a_min, a_dot );
            a_max = max( a_max, a_dot );
            b_min = min( b_min, b_dot );
            b_max = max( b_max, b_dot );
        }
        
        r32 overlap_max = min( a_max, b_max );
        r32 overlap_min = max( a_min, b_min );
        r32 overlap = overlap_max - overlap_min;
        
        if ( overlap <= 0 ) {
            
            result.axis.x = 0;
            result.axis.y = 0;
            result.magnitude = 0;
            result.direction = 0;
            break;
            
        } else if ( overlap < result.magnitude ) {
            
            result.axis = axis[ axis_index ];
            result.magnitude = overlap;
            result.direction = 1;
            
            if ( a_min < b_min ) {
                result.direciton = -1;
            }
        }
    }
    
    return result;
}

#define width 512
#define height 512
u32 buffer[ width * height * 4 ] = { 0 };

void draw_line( vec2_t p1, vec2_t p2, u32 color ) {
    
    r32 dx = fabsf( p2.x - p1.x );
    r32 dy = fabsf( p2.y - p1.y );
    
    if ( dx >= dy ) {
        
        if ( p1.x > p2.x ) {
            swap( p1, p2, vec2_t );
        }
        
        int sign = 1;
        
        if ( p1.y > p2.y ) {
            sign = -1;
        }
        
        r32 increment = dy / dx;
        
        u32 x = ( u32 ) p1.x;
        u32 x_end = ( u32 ) p2.x;
        
        u32 y = ( u32 ) p1.y;
        r32 error = 0.5f;
        
        while ( x <= x_end ) {
            
            buffer[ y * width + x ] = color;
            error += increment;
            
            if ( error >= 1.0f ) {
                y = ( u32 ) ( y + sign );
                error -= 1.0f;
            }
            x++;
        }
        
    } else {
        
        if ( p1.y > p2.y ) {
            swap( p1, p2, vec2_t );
        }
        
        int sign = 1;
        
        if ( p1.x > p2.x ) {
            sign = -1;
        }
        
        r32 increment = dx / dy;
        
        u32 y = ( u32 ) p1.y;
        u32 y_end = ( u32 ) p2.y;
        
        u32 x = ( u32 ) p1.x;
        r32 error = 0.5f;
        
        while ( y <= y_end ) {
            
            buffer[ y * width + x ] = color;
            error += increment;
            
            if ( error >= 1.0f ) {
                x = ( u32 ) ( x + sign );
                error -= 1.0f;
            }
            y++;
        }
    }
}

int main( int argc, char** argv ) {
    
    unsigned char tga_header[ 18 ] = {
        0,
        0,
        2,
        0,
        0,
        0,
        0,
        0,
        0,
        0,
        0,
        0,
        
        0, 0x2,
        
        0, 0x2,
        
        32,
        8,
    };
    
    vec2_t a_pos = { 255.0f, 255.0f };
    vec2_t b_pos = { 350.0f, 290.0f };
    
    for ( int step = 0; step < 150; step++ ) {
        
        vec2_t a[ 5 ] = {
            a_pos.x + 0.0f, a_pos.y - 50.0f,
            a_pos.x + 50.0f, a_pos.y + 0.0f,
            a_pos.x + 0.0f, a_pos.y + 50.0f,
            a_pos.x + -50.0f, a_pos.y + 0.0f,
        };
        
        a[ 4 ] = a[ 0 ];
        
        vec2_t b[ 5 ] = {
            b_pos.x + 0.0f, b_pos.y - 50.0f,
            b_pos.x + 50.0f, b_pos.y + 0.0f,
            b_pos.x + 0.0f, b_pos.y + 50.0f,
            b_pos.x + -50.0f, b_pos.y + 0.0f,
        };
        
        b[ 4 ] = b[ 0 ];
        
        sat_result_t result = sat( a, b );
        
        for ( int i = 0; i < width * height; i++ ) {
            buffer[ i ] = 0xff000000;
        }
        
        for ( int i = 0; i < 4; i++ ) {
            draw_line( a[ i ], a[ i + 1 ], 0xffffffff );
            draw_line( b[ i ], b[ i + 1 ], 0xffffffff );
        }
        
        if ( result.magnitude ) {
            vec2_t start = { 255.0f, 255.0f };
            vec2_t end = { 255.0f + result.axis.x * result.magnitude * result.direction, 255.0f + result.axis.y * result.magnitude * result.direction };
            draw_line( start, end, 0xffff0000 );
        }
        
        char filename[ ] = "render_000.tga";
        
        char c = ( char ) ( step / 100 );
        char d = ( char ) ( ( step - ( c * 100 ) ) / 10 );
        char u = ( char ) ( step - c * 100 - d * 10 );
        
        filename[ 7 ] = '0' + c;
        filename[ 8 ] = '0' + d;
        filename[ 9 ] = '0' + u;
        
        FILE* file = fopen( filename, "wb" );
        fwrite( tga_header, 18, 1, file );
        fwrite( buffer, 512 * 512 * 4, 1, file );
        fclose( file );
        
        b_pos.x -= 1;
        b_pos.y -= 1;
    }
    
    return 0;
}

Edited by Simon Anciaux on Reason: fixed code
Just wow, how can you be so good?! xD

Thanks so much, that was the tiny detail that was missing, so thankful for your response :D

Now i've got the sat collision implemented, and from here on i guess its all about experimenting with difference responses! =)
Once I had a visualization, it quickly became obvious what was the issue. Taking some time to create (good) visualization is always worth it.