|
Collision Detection (SAT) |
someone972
Member #7,719
August 2006
|
I read this tutorial about the Separating Axis Theorem. I understand the theory, I just don't know how to implement the axis checking.??? If anyone could help me out it would be greatly appreciated. EDIT: Nevermind, I finally figured it out. Update: Hopefully this helps anyone who comes across this post, I used the information in this tutorial, modifying the code to make it work, and the explanation of SAT in the link above. Take note that this only detects a collision, it doesn't provide any response, and it is only for polygon-polygon collisions, round objects have a different implementation. First we want an object that holds an x-y coordinate: class vector2d { public: int x,y; }; We then need to create an object that will hold the polygon data: class polygon2d { public: std::vector<vector2d> verticies; //this can be replaced with another //type of container if necessary int num_verticies; }; So far this should be pretty straight forward. Now we need the function that checks for collisions, it will be explained at the end:
This function returns 1 if there was a collision, 0 if there wasn't. And now on to explaining it. First: vector2d axis; double tmp,minA,maxA,minB,maxB; Axis is the coordinate that all the sides are projected onto. MinB, maxB, minA and maxA are the points that are projected the farthest apart, this is explained better later on. http://www.allegro.cc/files/attachment/593933 Next: for(int i = 0; i < p1.num_verticies;i++) { ... } This will loop through all the sides of the polygon, if you read the information on the page linked at the very top, you will know that all these sides need to be colliding for a collision to occur. http://www.allegro.cc/files/attachment/593934 Next: if(i == 0) { axis.x = p1.verticies[p1.num_verticies-1].y - p1.verticies[0].y; axis.y = p1.verticies[0].x - p1.verticies[p1.num_verticies-1].x; } else { axis.x = p1.verticies[i-1].y - p1.verticies<i>.y; axis.y = p1.verticies<i>.x - p1.verticies[i-1].x; } These lines of code will determine the axis from the side being suppiled from the for loop. http://www.allegro.cc/files/attachment/593935 To be continued... ______________________________________ |
De Baimbo
Member #8,944
August 2007
|
Interesting tecnique, but why should I create a new class "vector2d" instead of using a normal array, e.g. coords[2], to store the x and y coordinates of a vertex? |
nonnus29
Member #2,606
August 2002
|
The choice on how represent vectors is completely arbitrary. You'll see different projects do it with arrays or structs of individual coordinates. It does make interoperating with things difficult at times; like if you want to use ODE (open dynamics engine) with your code and you've coded math one way and they've done it another. Nice pictures by the way, did you make them? |
|