vendredi 24 juillet 2015

2D Elastic Collision with SFML

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 balls of equal mass in SFML C++. 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: enter image description here

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:

vector<sf::CircleShape> balls;
vector<Vector2f> Xvelocities // (magnitudes, directions)
vector<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?

Aucun commentaire:

Enregistrer un commentaire