原理
思路:
面积和:
abc == obc+aoc+abo,应该有更简洁的方法,但是这个方法思路更简单
代码实现:
注意二维向量的叉乘后,是垂直于平面的向量,相当于z为0三维向量叉乘,所以只有z维度有值,xy=0.
float值不要直接==,考虑作差或者用库函数。
#include <string>
#include <math.h>
using namespace std;
struct Vec {
float x_;
float y_;
Vec() {}
float dot(const Vec &other) {
return sqrt(x_ * x_ + y_ * y_);
}
float cross_norm(const Vec &other) {
// Vec3d {y0*z1-z0-y1, -(x0*z1-z0*x1), x0*y1-x1*y0}
float Vec3d_z = x_ * other.y_ - y_ * other.x_;
return fabs(Vec3d_z);
}
};
struct Point {
float x_;
float y_;
Point() {}
Point(const float &x, const float &y) : x_(x), y_(y) {}
Vec operator-(const Point &other) const {
Vec res;
res.x_ = x_ - other.x_;
res.y_ = y_ - other.y_;
return res;
}
};
struct Triangle {
Point A_;
Point B_;
Point C_;
Triangle(const Point &A, const Point &B, const Point &C) : A_(A), B_(B), C_(C) {}
float get_area() const {
Vec a = A_ - B_;
Vec b = A_ - C_;
return a.cross_norm(b) / 2;
}
};
float get_area(const Triangle &tmp) {
return tmp.get_area();
}
int main() {
Point A(0.0, 0.0);
Point B(1.0, 2.0);
Point C(2.0, 1.0);
Point O(1.5, 1.49);
float area_ABC = get_area(Triangle(A, B, C));
float area_OBC = get_area(Triangle(O, B, C));
float area_AOC = get_area(Triangle(A, O, C));
float area_ABO = get_area(Triangle(A, B, O));
bool in_tri = fabs(area_ABC - (area_OBC + area_AOC + area_ABO)) < 0.0001; // notify : cannot float A == float B
if (in_tri)
printf("Point in Triangle");
else
printf("Point Not in Triangle");
return 0;
}