Created
October 8, 2016 13:59
-
-
Save MrSapps/444a5c98a6e6064790a68f9b5e6176d5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
bool raycast_map(const std::vector<Oddlib::Path::CollisionItem>& lines, const glm::vec2& line1p1, const glm::vec2& line1p2, int collisionType, Physics::raycast_collision* const collision) | |
{ | |
const Oddlib::Path::CollisionItem* nearestLine = nullptr; | |
float nearestCollisionX = 0; | |
float nearestCollisionY = 0; | |
float nearestDistance = 0.f; | |
bool hasCollided = false; | |
bool firstCollision = true; | |
for (const Oddlib::Path::CollisionItem& line : lines) | |
{ | |
if (line.mType != collisionType) { continue;} | |
float intersectionX = 0; | |
float intersectionY = 0; | |
float line1p1x = line1p1.x; | |
float line1p1y = line1p1.y; | |
float line1p2x = line1p2.x; | |
float line1p2y = line1p2.y; | |
float line2p1x = line.mP1.mX; | |
float line2p1y = line.mP1.mY; | |
float line2p2x = line.mP2.mX; | |
float line2p2y = line.mP2.mY; | |
// Get the segments' parameters. | |
float dx12 = line1p2x - line1p1x; | |
float dy12 = line1p2y - line1p1y; | |
float dx34 = line2p2x - line2p1x; | |
float dy34 = line2p2y - line2p1y; | |
// Solve for t1 and t2 | |
float denominator = (dy12 * dx34 - dx12 * dy34); | |
float t1 = ((line1p1x - line2p1x) * dy34 + (line2p1y - line1p1y) * dx34) / denominator; | |
if (isinf(t1)) | |
continue; | |
float t2 = ((line2p1x - line1p1x) * dy12 + (line1p1y - line2p1y) * dx12) / -denominator; | |
// Find the point of intersection. | |
intersectionX = line1p1x + dx12 * t1; | |
intersectionY = line1p1y + dy12 * t1; | |
// The segments intersect if t1 and t2 are between 0 and 1. | |
hasCollided = ((t1 >= 0) && (t1 <= 1) && (t2 >= 0) && (t2 <= 1)); | |
if (hasCollided) | |
{ | |
float distance = sqrtf(powf((line1p1x - intersectionX), 2) + powf((line1p1y - intersectionY), 2)); | |
if (firstCollision || distance < nearestDistance) | |
{ | |
nearestCollisionX = intersectionX; | |
nearestCollisionY = intersectionY; | |
nearestDistance = distance; | |
nearestLine = &line; | |
firstCollision = false; | |
} | |
} | |
if (nearestLine) | |
{ | |
if (collision) | |
{ | |
collision->intersection.x = nearestCollisionX; | |
collision->intersection.y = nearestCollisionY; | |
} | |
//*collisionX = (int)(nearestCollisionX * 0x10000); | |
//*collisionY = (int)(nearestCollisionY * 0x10000); | |
//*collision = nearestLine; | |
return true; | |
} | |
} | |
return false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment