AutoMove Circle Shape

Hi, I was looking for some help to try and understand how i can get a circleshape (SFML Library) to move across the page like how you would find in a game of pong. I have managed to define the settings for the shape as follows:

CircleShape ball;
ball.setRadius(22); // circle size
ball.setPosition(300, 236);

If somebody could please advise or help me understand the logics in trying to get this to move across the screen from right to left.

Sorry for the vague question, want to make sure I have an understanding rather just having the code.
Quick example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <SFML/Graphics.hpp>

int main()
{
    sf::Vector2f windowSize(800, 600);
    sf::RenderWindow window(sf::VideoMode(windowSize.x, windowSize.y), "SFML works!");

    sf::CircleShape circle(10.f);
    circle.setOrigin(5, 5);
    circle.setFillColor(sf::Color::Green);

    sf::Vector2f velocity;
    velocity.x = 1;
    velocity.y = 1;

    while (window.isOpen())
    {
        sf::Event event;
        while (window.pollEvent(event))
        {
            if (event.type == sf::Event::Closed)
                window.close();
        }

        //move the ball
        sf::Vector2f pos = circle.getPosition();
        pos += velocity;
        circle.setPosition(pos);


        //Change the direction of the ball when the ball is off the screen
        if(circle.getPosition().x < 0 || circle.getPosition().x > windowSize.x)
            velocity.x *= -1;
        else if(circle.getPosition().y < 0 || circle.getPosition().y > windowSize.y)
            velocity.y *= -1;


        window.clear();
        window.draw(circle);
        window.display();
    }

    return 0;
}
Last edited on
Yanson, thanks for that really appreciate it, managed to add it within my code, and works but got a few questions just to get an understanding of how it works.

I have noticed that if i come out of the window and go back in the speed of the ball reduces and gets slower and slower, what part of the code actually does this?

Also the windowSize is perfect for the ball to bounce off, but what if i was to add a border across all four sides using RectangleShape (example below)

RectangleShape toprectangle;
toprectangle.setPosition(0, 0);
toprectangle.setSize(Vector2f(716, 33));

what part of the code would i have to change in order for the ball to bounce of the borders rather than the actual windowSize?

Thanks once again for all your help, really appreciate it.
Topic archived. No new replies allowed.