/Billiards

Just a simple billiards game written in C++ using SDL2 library purpose for studying and learning geometry math.

Primary LanguageC++

Billiards

Applications of geometry in billiards game programming

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.

What are vectors used for?

  • They are used to determine an object's position, or velocity.

What are trigonometric used for?

  • They are used for the purpose of calculating the angle of an object.

How did I apply them in programming

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?

  1. First we need to calculate the opposite side:

  2. Next, we have to calculate the hypotenuse side:

  3. After calculate the opposite, hypotenuse sides then we calculate the angle of the stick (use inverse sine):

  4. We need to check if x1 > x2 then the angle = 180° - angle: angle = 180 - angle.

  5. 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);