【问题标题】:SFML animation without keyboard input无键盘输入的 SFML 动画
【发布时间】:2016-03-06 00:02:49
【问题描述】:

我目前正在开展一个项目,该项目基本上是排序算法的可视化,以解释它们的工作原理(而不是概述)。我是使用 SFML(甚至 OpenGL)的新手,并且对库的经验有限,但我想做的是将绘制的精灵移动到不同的位置以显示排序。我查看了教程和示例,但它们都采用键盘输入来移动精灵——这个项目中没有使用。有谁知道具体如何实现这一目标?

这是当前代码:

DrawCups.h

class DrawCups
{
public:
    DrawCups(sf::RenderWindow& window);
    ~DrawCups();

    void loadImage(const char* pathname, sf::Texture& texture, sf::Sprite& sprite);

    void drawCup1();

private:
    sf::RenderWindow& _window;
};

DrawCups.cpp(选定函数)

void DrawCups::drawCup1()
{
    // load our image
    sf::Texture cup1;        // the texture which will contain our pixel data
    sf::Sprite cup1Sprite;         // the sprite which will actually draw it
    loadImage("./images/InsertionSort/red_cup_1.png", cup1, cup1Sprite);
    cup1Sprite.setPosition(sf::Vector2f(150, 230));
    _window.draw(cup1Sprite);
}

main.cpp

int main()
{
    sf::RenderWindow window(sf::VideoMode(1366, 768), "Sorting Algorithm Visualisation: SFML");
    window.setFramerateLimit(60);

    while (window.isOpen())
    {
        sf::Event event;
        while (window.pollEvent(event))
        {
            if (event.type == sf::Event::Closed)
                window.close();
        }
        window.clear(sf::Color::White);
        DrawCups drawToWindow(window);;
        drawToWindow.drawCup1();
        window.display();
    }

    return 0;
}

【问题讨论】:

  • 每次需要重绘时都更新图像有什么问题?
  • 它需要从它的原始位置平滑地移动到排序区域。重新绘制精灵会使动画变得不连贯。
  • 您必须重新绘制精灵以使其移动。如果动画太不稳定,要么是你重绘它的速度不够快,要么是你改变它的位置太快了。
  • 你能举个例子吗?

标签: c++ opengl sfml


【解决方案1】:

在循环之前创建图像并在绘制之前对其进行更新。

DrawCups drawToWindow(window); //Constructor creates the sprite

while (window.isOpen())
{
    ...
    drawToWindow.update(); //Update the position

    //Redraw
    window.clear(sf::Color::White);
    drawToWindow.drawCup1();
    window.display();
}

我不确定你想要什么类型的运动,但更新功能可以是这样的:

void DrawCups::update()
{
    sf::Vector2f pos = this->cup1Sprite.getPosition();
    pos.x++; //Move 1 pixel to the left
    this->cup1Sprite.setPosition(pos);
}

显然改变机芯以满足您的需求。如果移动太快或太慢,请进行更小/更大的更新。

【讨论】:

  • 太棒了。谢谢你的例子。 :)
  • 嗯,您提供的代码只会使屏幕闪烁 - 不会移动元素本身。我已经使用比 1 更大的像素范围对其进行了测试。
  • 我目前无法测试我的代码,所以可能有错误。你确定你正确地更新了位置吗?确保您的绘图功能不会像以前那样重置位置。
  • 也许我当时用错了位置,因为我已经用 .rotate 试过了,效果很好。我目前正在使用 pos.x+10; - 这是不正确的吗?
  • 您的意思可能是pos.x+=10;pos.x+10 对结果没有任何作用。
猜你喜欢
  • 2012-12-27
  • 1970-01-01
  • 1970-01-01
  • 2021-08-19
  • 2019-03-01
  • 2012-05-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多