Billiards game is a game that uses geometric math a lot, and I made this game for the purpose of learning, studying, and improving my geometric math.
To make this game we'll need to apply a lot of geometry math, here we use vectors and trigonometry.
- They are used to determine an object's position, or velocity.
- They are used for the purpose of calculating the angle of an object.
For example, we have ball position (x1: 400; y1: 290) and mouse position (x2: 1107; y2: 12).
How do we calculate the angle of the stick?
-
First we need to calculate the opposite side:
-
Next, we have to calculate the hypotenuse side:
-
After calculate the opposite, hypotenuse sides then we calculate the angle of the stick (use inverse sine):
-
We need to check if x1 > x2 then the angle = 180° - angle:
angle = 180 - angle
. -
If the angle < 0 then the angle will add 360°:
angle += 360
.
Finally the angle of the stick is 158.524°.
Full of the code:
double opposite = vector2.getY() - vector.getY();
double hypotenuse = std::hypot(vector2.getX() - vector.getX(), vector2.getY() - vector.getY());
double degrees = (std::asin(opposite / hypotenuse) * 180) / PI + 180;
if (vector.getX() > vector2.getX()) degrees = 180 - degrees;
if (degrees < 0) degrees += 360;
stick->setAngle(degrees);