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
|
#include <iostream>
#include <cmath>
class vec2f {
public :
vec2f() { x = y = 0; };
vec2f(float _x, float _y) { x = _x; y = _y; }
float x, y;
};
class Entity {
public :
Entity() { dimension = vec2f(1.0, 1.0); }
bool isColliding(const Entity* entity, vec2f& collisionVector);
vec2f position;
vec2f dimension;
};
class Block : public Entity {
public :
Block() : Entity() {}
};
class Player : public Entity {
public :
Player() : Entity() {}
};
bool Entity::isColliding(const Entity* entity, vec2f& collisionVector) {
//The collision vector can be used to move either of the intersecting entities.
float xIntersect = (dimension.x + entity->dimension.x) - (fabs(dimension.x - entity->dimension.x));
float yIntersect = (dimension.y + entity->dimension.y) - (fabs(dimension.y - entity->dimension.y));
if (xIntersect <= 0 || yIntersect <= 0) { return false; }
if (xIntersect <= yIntersect) {
collisionVector.x += xIntersect * (dimension.x < entity->dimension.x ? -1.0 : 1.0);
}
else {
collisionVector.y += yIntersect * (dimension.y < entity->dimension.y ? -1.0 : 1.0);
}
return true;
}
/*
The dimensions of the entities are set up kind of funky.
If dimension.x = 1, and dimension.y = 1, then the entity will be 2x2.
This is so, because the origin of each object is at the exact center, as opposed to one of the sides.
So really, the dimensions are half-lengths of each dimension.
The following entity has a 2x2 bounding box, because it's dimensions are 1 and 1.
<-1-><-1->
*--------*^
| |1
| |v
| |^
| |1
*--------*v
*/
int main() {
vec2f collisionVector;
Player* player = new Player();
Block* block = new Block();
/*By default, the player and the block will be colliding, because I haven't explicitly overwritten the values of the position vectors*/
std::cout << "The player and the block are" << (player->isColliding(block, collisionVector) ? "" : "n't") << " colliding!" << std::endl;
std::cout << "Collision Vector:\t" << "[" << collisionVector.x << ", " << collisionVector.y << "]" << std::endl;
std::cin.get();
delete player;
delete block;
return 0;
}
|