MATH: Fix Line2d intersection functions. Fix #682

This commit is contained in:
Giulio Camuffo 2013-01-09 18:27:07 +01:00
parent 2df6123718
commit 00a42f3d85
2 changed files with 24 additions and 16 deletions

View File

@ -32,8 +32,13 @@ Line2d::Line2d() :
Line2d::Line2d(const Vector2d &direction, const Vector2d &point) {
Vector2d d = direction;
if (fabsf(d.getX()) > 0.0001f) {
_a = d.getY() / d.getX();
_b = -1;
} else {
_a = 1;
_b = 0;
}
if (_b == 0) {
_c = -point.getX();
@ -76,23 +81,18 @@ bool Line2d::intersectsLine(const Line2d &line, Vector2d *pos) const {
float x, y;
if (d * b - a * e == 0 || a == 0) {
const float det = a * e - b * d;
if (fabsf(det) < 0.0001f) {
return false;
}
if (!pos) {
return true;
}
/*
* {ax + by + c = 0 -> x = -(by + c) / a
* {dx + ey + f = 0 -> y = (-dc + af) / (db - ae)
*/
y = (-d * c + a * f) / (d * b - a * e);
x = -(b * y + c) / a;
x = (-c * e + b * f) / det;
y = (-a * f + c * d) / det;
if (pos)
*pos = Vector2d(x, y);
return true;
}

View File

@ -129,9 +129,17 @@ bool Rect2d::intersectsCircle(const Vector2d &center, float radius) const {
}
}
inline bool le(float a, float b) {
return (a < b || (fabsf(a - b) < 0.0001f));
}
inline bool ge(float a, float b) {
return (a > b || (fabsf(a - b) < 0.0001f));
}
bool Rect2d::containsPoint(const Vector2d &point) const {
return (point.getX() >= _topLeft.getX() && point.getX() <= _bottomRight.getX() &&
point.getY() >= _topLeft.getY() && point.getY() <= _bottomRight.getY());
return ge(point.getX(), _topLeft.getX()) && le(point.getX(), _bottomRight.getX()) &&
ge(point.getY(), _topLeft.getY()) && le(point.getY(), _bottomRight.getY());
}
Vector2d Rect2d::getCenter() const {