Skip to content

Instantly share code, notes, and snippets.

@lcpz
Last active February 26, 2022 03:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lcpz/cab70d24899ec482fa62907fc075f129 to your computer and use it in GitHub Desktop.
Save lcpz/cab70d24899ec482fa62907fc075f129 to your computer and use it in GitHub Desktop.
#include <iostream>
struct Point { // 2-D
double x, y;
Point(double x, double y) : x(x), y(y) {}
};
// Barycentric method - https://stackoverflow.com/a/9755252
bool isInsideTriangle(const Point& a, const Point& b, const Point& c, const Point& s)
{
// collinearity, (a, b, c) is not a triangle
if (a.x == b.x == c.x || a.y == b.y == c.y)
return false;
double as_x = s.x - a.x;
double as_y = s.y - a.y;
bool s_ab = (b.x - a.x) * as_y - (b.y - a.y) * as_x > 0;
if ((c.x - a.x) * as_y - (c.y - a.y) * as_x > 0 == s_ab) return false;
if ((c.x - b.x) * (s.y - b.y) - (c.y - b.y) * (s.x - b.x) > 0 != s_ab) return false;
return true;
}
int main()
{
Point origin{0, 0};
Point p1{-340, 495};
Point p2{-153, -910};
Point p3{835, -947};
std::cout << std::boolalpha << isInsideTriangle(p1, p2, p3, origin) << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment