Added collision detection method to PhysicsObject. Not tested.
--- a/src/PhysicsObject.cc Sun Dec 07 22:15:21 2008 +0000
+++ b/src/PhysicsObject.cc Sun Dec 07 22:36:38 2008 +0000
@@ -394,3 +394,30 @@
return 0.0;
}
+bool PhysicsObject::collides (const PhysicsObject &obj) {
+ const std::vector<Vector> oShape = obj.getShape();
+ Vector p1, p2, p3;
+ int8_t sign, nsign;
+ for (std::vector<Vector>::const_iterator i = oShape.begin(); i != oShape.end(); i++) { // For every point in other shape
+ p3 = *i + obj.getPosition();
+ sign = 0;
+ for (std::vector<Vector>::const_iterator j = shape.begin(); j != shape.end(); j++) {
+ p1 = *j + position;
+ if ( (j+1) == shape.end() ) p2 = *shape.begin() + position;
+ else p2 = *(j+1) + position;
+ nsign = crossProduct(p1, p2, p3);
+ if ( sign == 0 ) sign = nsign;
+ else if ( ((sign < 0) && (nsign < 0)) || ((sign > 0) && (nsign > 0)) ) continue;
+ else return false;
+ }
+ }
+ return true;
+}
+
+int8_t crossProduct (const Vector &p1, const Vector &p2, const Vector &p3) {
+ float p = (p2.x - p1.x)*(p3.y - p1.y) - (p2.y - p1.y)*(p3.x - p1.x);
+ if (p < 0)
+ return -1;
+ else
+ return 1;
+}
--- a/src/PhysicsObject.hh Sun Dec 07 22:15:21 2008 +0000
+++ b/src/PhysicsObject.hh Sun Dec 07 22:36:38 2008 +0000
@@ -240,6 +240,13 @@
void setPivot (PhysicsObject *pivot);
/**
+ * Checks if object collides with other objects
+ *
+ * @param obj Other PhysicsObject
+ */
+ bool collides (const PhysicsObject &obj);
+
+ /**
* Compute the force that this object (as a pivot) exerts on the given object
*/
virtual float getPivotForce (PhysicsObject *bob);
@@ -255,4 +262,16 @@
Vector dv; // Acceleration
};
+/**
+ * Returns the "sign" of the cross product between given points. In
+ * practice the sign of the return value tels on which side of the
+ * line drawn between p1 and p2 the point p3 is.
+ *
+ * @param p1 Line start point
+ * @param p2 Line end point
+ * @param p3 Point
+ * @return Variable, the sign of which tells on which side of the line p3 is.
+ */
+int8_t crossProduct(const Vector &p1, const Vector &p2, const Vector &p3);
+
#endif