Sign in to follow this  

Sfml Circle Collision

Recommended Posts

Hello! I'm Moritz and right now I'm programming a game in c++ with SFML and my problem is:

A resolving of a collision between two circles. Although I can detect the collision between these two circles, I can not resolve it and don't know what I'm doin' wrong.


Here's my code:




#include <SFML\Graphics.hpp>
#include <math.h>
#include <cmath>
#include <iostream>
using namespace sf;

bool Collision(sf::CircleShape* a, sf::CircleShape* b) {
    float a_square = pow(a->getPosition().x - b->getPosition().x, 2);
    float b_square = pow(a->getPosition().y - b->getPosition().y, 2);

    if (sqrt(a_square + b_square) >=
        a->getRadius() + b->getRadius()) {
        return false;
    else {
        a->move(a->getPosition().x - b->getPosition().x, a->getPosition().y - b->getPosition().y);
        return true;

int main()

    RenderWindow app(VideoMode(800, 600), "Car Racing Game!");

    sf::CircleShape circle;
    circle.setPosition(400, 300);

    sf::CircleShape circle2;
    circle2.setPosition(500, 300);


    while (app.isOpen())
        Event e;
        while (app.pollEvent(e))
            if (e.type == Event::Closed)

        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left)) {
            circle.move(-1, 0);

        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right)) {
            circle.move(1, 0);

        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up)) {

        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down)) {
            circle.move(0, 1);

        if (Collision(&circle, &circle2)) {






Share this post

Link to post
Share on other sites
Works for me. On collision, the red circle you control flashes quickly to white and back to red then moves/jumps away quickly at an angle.

What kind of resolve were you hoping for?

ED: Almost forgot, If you want to knock the other circle around, change all the a-> to b-> and vice versa on this line...
a->move(a->getPosition().x - b->getPosition().x, a->getPosition().y - b->getPosition().y); Edited by fleabay

Share this post

Link to post
Share on other sites

You have the distance to the circles already d = |B - A|.

Nows its just a simple matter of subtracting that distance from the sum of both radius - now you have the separation/penetration distance. Last thing you need is the direction / normal of the distance which is simple B-A / |B-A|.


Now you have everything you need to resolve the collision in any way you want.

Edited by Finalspace

Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this