【问题标题】:Centering Shapes/Objects in SFML for C++在 SFML for C++ 中居中形状/对象
【发布时间】:2014-02-13 02:24:09
【问题描述】:

所以最近,我开始使用 SFML 在 Visual Studio 中制作游戏。 在设置完所有内容并编写了一些示例代码后,我设计了这个:

#include <SFML/Graphics.hpp>

int main()
{
    sf::RenderWindow window(sf::VideoMode(600, 600), "Move the Shape");
    sf::CircleShape shape(100.f);
    shape.setFillColor(sf::Color::Green);
    while (window.isOpen())
    {
        sf::Event event;
        while (window.pollEvent(event))
        {
            if (event.type == sf::Event::Closed)
                window.close();
        }

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

    return 0;
}

程序产生以下结果:

如何将圆圈放在中心?之后我想设置一些代码,让用户使用键盘的箭头键移动圆圈,所以我需要圆圈在中心。

【问题讨论】:

    标签: c++ visual-c++ visual-studio-2012 sfml


    【解决方案1】:

    您需要将shape 的位置设置为shape.setPosition(x, y)。您知道窗口的宽度和高度(单向 600px),并且您知道圆的半径(100px),因此您可以计算出圆需要移动才能居中的 x 和 y。我会把它留给你做练习。

    您可能还需要考虑设置圆的原点,以便您可以通过圆心定位它(请参阅setOrigin)。

    【讨论】:

    • 我自己刚刚发现了这一点,但感谢您告诉我有关 setOrigin 部分的信息。
    【解决方案2】:

    实际上,我已经回答了我自己的问题。要设置项目的位置,请编写:

    shape.setPosition(x, y);
    

    【讨论】:

      【解决方案3】:

      如果你想让一个圆圈居中,你可以这样做

      circle.setPosition((window.getSize().x / 2.f) - circle.getRadius(), (window.getSize().y / 2.f) - circle.getRadius());
      

      【讨论】:

      • 矩形呢?
      【解决方案4】:

      首先,你应该将圆的原点设置在它的中间:

      circle.setOrigin( circle.getRadius() / 2 , circle.getRadius() / 2 );

      那个,把圆心移到碎石中间:

      circle.setPosition( window.getSize().x / 2 , window.getSize().y / 2 );
      

      【讨论】:

      • 我认为您不会想将半径除以二(您在考虑直径吗?)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-05-09
      • 1970-01-01
      • 1970-01-01
      • 2020-09-03
      • 1970-01-01
      • 1970-01-01
      • 2014-12-28
      相关资源
      最近更新 更多