I'm a complete beginner to OOP and I'm trying to figure out the best way to write a program for 2D collision of circles of equal mass in SFML C++. I want to generate two or more circles in a box with set starting velocity, but random starting position and direction, then have them interact. I'm having a lot of difficulty with the pseudocode for the mechanics since my physics is very rusty. I found this equation for 2D elastic collisions on wiki:
Does this mean that I should use this for both the x and y coordinates for each ball? I was thinking of doing something like this for the balls and velocities:
std::vector<sf::CircleShape> balls;
std::vector<sf::Vector2f> Xvelocities; // (magnitudes, directions)
std::vector<sf::Vector2f> Yvelocities; // (magnitudes, directions)
and I wrote a collision function like this:
bool Collision_Detection(sf::CircleShape &ball1, sf::CircleShape &ball2)
{
bool collision = false;
float distance = sqrt(pow(ball2.getPosition().x - ball1.getPosition().x, 2) +
pow(ball2.getPosition().y - ball1.getPosition().y, 2));
if (distance <= ball1.getRadius() + ball2.getRadius() + 4)
collision = true;
return collision;
The detection sometimes works and sometimes gets stuck, I'm not sure if it's a problem with the logic or if the performance is bad and I need to do bounding-box collision first.
Does how I'm going about this make any sense? Is there something I'm overlooking or a more standard way that people usually code this?