Search code examples
c++sfml

C++ SFML, orbiting


I recently started to learn SFML, and I have a question, how to make what would be the second body moving in an orbit, help please.

#include <SFML/Graphics.hpp>
using namespace sf;
int main()
{
   RenderWindow window(VideoMode(800, 600), "Hello, world!");

    CircleShape shape(50.f);
    shape.setFillColor(Color::Black);
    shape.setPosition(400,300);
    shape.setOrigin(50,50);

    CircleShape shape2(10.f);
    shape2.setFillColor(Color::Black);
    shape2.setPosition(700,500);
    shape2.setOrigin(10,10);

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

        }
        window.clear(Color::White);
        window.draw(shape);
        window.draw(shape2);
        window.display();
    }
    return 0;
}

Solution

  • Well... I will not post full solution. It would not be educational to give you complete code. But I will give you some hints :) .

    1. Your world update should happen in the loop. In the while loop. You have two there. Which one do you think is the one which updates your world?
    2. Circle equation in Cartesian coordinate system is: (x-a)^2 + (y-b)^2 = r^2
    3. In the loop from 1 you should use equation from 2 to update coordinates of second object (shape2).
    4. To perform action from point 3 you have two possibilities: function setPosition and function move, both members of class CircleShape.

    If you have further questions ask them in the comments.

    For your future questions on stack: give us proof that you put some effort in resolving problem. If question looks like the one I'm answering now we have the idea that you did not think about it just posted it here and you are waiting for someone to write your code for you.