summaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/game-server/collisiondetection.cpp14
-rw-r--r--src/utils/fastsqrt.h23
2 files changed, 31 insertions, 6 deletions
diff --git a/src/game-server/collisiondetection.cpp b/src/game-server/collisiondetection.cpp
index 907129ad..8fdd50e5 100644
--- a/src/game-server/collisiondetection.cpp
+++ b/src/game-server/collisiondetection.cpp
@@ -25,6 +25,7 @@
#include "point.h"
#include <cmath>
+#include "utils/fastsqrt.h"
bool
Collision::circleWithCirclesector( const Point& circlePos, int circleRadius,
@@ -35,7 +36,8 @@ Collision::circleWithCirclesector( const Point& circlePos, int circleRadius,
//calculate distance
int distX = circlePos.x - secPos.x;
int distY = circlePos.y - secPos.y;
- float dist = sqrt(distX * distX + distY * distY);
+ float invDist = fastInvSqrt(distX * distX + distY * distY);
+ float dist = 1.0f / invDist;
//if out of range we can't hit it
if (dist > secRadius + circleRadius) {
@@ -49,13 +51,13 @@ Collision::circleWithCirclesector( const Point& circlePos, int circleRadius,
//calculate target angle
if (distX > 0)
{
- targetAngle = asin(-distY / dist);
+ targetAngle = asin(-distY * invDist);
} else {
if (distY < 0)
{
- targetAngle = M_PI - asin(-distY / dist);
+ targetAngle = M_PI - asin(-distY * invDist);
} else {
- targetAngle = -M_PI - asin(-distY / dist);
+ targetAngle = -M_PI - asin(-distY * invDist);
}
}
@@ -69,7 +71,7 @@ Collision::circleWithCirclesector( const Point& circlePos, int circleRadius,
//Add hit circle
- secSize += asin(circleRadius/dist) * 2;
+ secSize += asin(circleRadius * invDist) * 2;
- return (targetDiff < secSize / 2.0f);
+ return (targetDiff < secSize * 0.5f);
}
diff --git a/src/utils/fastsqrt.h b/src/utils/fastsqrt.h
new file mode 100644
index 00000000..8ba6f8ce
--- /dev/null
+++ b/src/utils/fastsqrt.h
@@ -0,0 +1,23 @@
+/* A very fast function to calculate the approximate inverse square root of a
+ * floating point value and a helper function that uses it for getting the
+ * normal squareroot. For an explanation of the inverse squareroot function
+ * read:
+ * http://www.math.purdue.edu/~clomont/Math/Papers/2003/InvSqrt.pdf
+ *
+ * Unfortunately the original creator of this function seems to be unknown.
+ */
+
+float fastInvSqrt(float x)
+{
+ float xhalf = 0.5f*x;
+ int i = *(int*)&x;
+ i = 0x5f375a86- (i>>1);
+ x = *(float*)&i;
+ x = x*(1.5f-xhalf*x*x);
+ return x;
+}
+
+float fastSqrt(float x)
+{
+ return 1.0f/fastInvSqrt(x);
+}