Skip to content

Instantly share code, notes, and snippets.

@LindseyB
Created May 8, 2010 12:27
Show Gist options
  • Save LindseyB/394536 to your computer and use it in GitHub Desktop.
Save LindseyB/394536 to your computer and use it in GitHub Desktop.
// checks for collisions using the separating axis theorem
bool VWCar::isColliding(VWCollisionObject* colObj){
int i;
// define the axes: 2 from collision object 2 from car
vector<ofxVec2f*> axes;
axes.reserve(4);
vector<ofxVec2f*>* objCorners = colObj->getCorners();
if(objCorners->empty()){
return false;
}
for(i = 0; i < 4; i++){
ofxVec2f* axis = new ofxVec2f();
axes.push_back(axis);
}
// cornersAbs is a vector that holds the coordinates for the corners of the car that is colliding
axes[0]->set(cornersAbs[0]->x - cornersAbs[1]->x, cornersAbs[0]->y - cornersAbs[1]->y);
axes[1]->set(cornersAbs[0]->x - cornersAbs[3]->x, cornersAbs[0]->y - cornersAbs[3]->y);
axes[2]->set(objCorners->at(0)->x - objCorners->at(1)->x, objCorners->at(0)->y - objCorners->at(1)->y);
axes[3]->set(objCorners->at(0)->x - objCorners->at(3)->x, objCorners->at(0)->y - objCorners->at(3)->y);
// perpendicular actually finds the normalized vector perpendicular to the one it operates on
// for the sake of this algorithm it doesn't actually need to be normalized
for(i = 0; i < 4; i++){
axes[i]->perpendicular();
}
float minCar;
float maxCar;
float minObj;
float maxObj;
float scalarCar;
float scalarObj;
// for each axis project the objects onto the axis
for(i = 0; i < 4; i++){
// for each corner of the object dot it with the axis
for (int j = 0; j < 4; j++) {
scalarCar = ((cornersAbs[j]->x * axes[i]->x) + (cornersAbs[j]->y * axes[i]->y));
scalarObj = ((objCorners->at(j)->x * axes[i]->x) + (objCorners->at(j)->y * axes[i]->y));
if(j == 0){
minCar = scalarCar;
maxCar = scalarCar;
minObj = scalarObj;
maxObj = scalarObj;
}
// record the min and max for each object
if(scalarCar < minCar){
minCar = scalarCar;
}
if(scalarCar > maxCar){
maxCar = scalarCar;
}
if(scalarObj < minObj){
minObj = scalarObj;
}
if(scalarObj > maxObj){
maxObj = scalarObj;
}
}
// if they don't overlap then they aren't colliding
if(minObj > maxCar || maxObj < minCar || minCar > maxObj || maxCar < minObj){
// clean up
while(!axes.empty()){
ofxVec2f* temp = axes.at(axes.size()-1);
axes.pop_back();
delete temp;
}
return false;
}
}
// clean up
while(!axes.empty()){
ofxVec2f* temp = axes.at(axes.size()-1);
axes.pop_back();
delete temp;
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment