-
Notifications
You must be signed in to change notification settings - Fork 1
/
gamemath.cpp
73 lines (66 loc) · 1.91 KB
/
gamemath.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#include "gamemath.h"
// Returns the angle of the point acording to the origin
// Result should be in [0, 2*PI)
qreal angle(QPointF point, QPointF origin)
{
qreal dx = point.x() - origin.x();
qreal dy = origin.y() - point.y();
qreal result = qAtan(qAbs(dy / dx));
if (dx < 0 && dy >= 0)
return PI - result;
if (dx <= 0 && dy < 0)
return PI + result;
if (dx > 0 && dy < 0)
return 2 * PI - result;
if (result != result) // NaN !!!
return 0;
return result;
}
// Calculate the position acording to the angle, radius and origin
QPointF calculatePosition(qreal a, qreal r, QPointF origin)
{
qreal dx = qCos(a) * r;
qreal dy = -qSin(a) * r;
if ((PI - a < 0.02 && PI - a > -0.02))
{
if (dx < 0)
dx = -r;
else
dx = r;
dy = 0;
}
qreal x = dx + origin.x();
qreal y = dy + origin.y();
return QPointF(x, y);
}
// When the translate path is ^, suppose that the distance between begin
// position and end position is 1, inputs the x position, returns the y
// position(I should draw a picture to show how it works-.-)
qreal bridgeY(qreal bridgeX)
{
if (bridgeX <= 0 || bridgeX >= 1)
return 0;
qreal dx = qAbs(0.5 - bridgeX);
return qSqrt(1 - qPow(dx, 2)) - 0.8660;
}
// Distance of two points
qreal distanceOfTwoPoints(QPointF p1, QPointF p2)
{
return qSqrt(qPow(p1.x() - p2.x(), 2) + qPow(p1.y() - p2.y(), 2));
}
// Distance from the center with the angle, helps to calculate the distance
// from the center and locate the balls on the hexagon
qreal distanceFromTheCenterWithTheAngle(qreal angle, qreal maxR)
{
while (angle < 0)
angle += PI / 3;
while (angle >= PI / 3)
angle -= PI / 3;
return maxR * qSin(PI / 3) / qSin(2 * PI / 3 - angle);
}
// Calculate a new position from the original position and scale rate in 2
// directions
QPointF scale(QPointF originalPos, double xRate, double yRate)
{
return QPointF(xRate * originalPos.x(), yRate * originalPos.y());
}