SFML 中的动画形状?

Animating shapes in SFML?

我只是想制作一个简单形状的动画(例如矩形)。这个动画只是关于当你按下一个确定的键时改变形状的颜色

我找不到任何用于这个简单目的的教程,这些在线教程都是关于精灵移动等等。

通过创建一个名为 'Transition' 的 class 和其中一个名为 'Transition::update()' 的函数,设法做到了 颜色变化,这只是更改在此 class 中创建的形状的颜色。代码很简单(认为没有必要把它放在这里)。 问题是我做的这个动画不是流畅的动画,只是在适当的时候改变颜色。

问题很明显:

How could I give that smoothness to my animation?

(不需要在这里放大代码,只是一个快速的建议就可以了)

基本上你需要引入存储颜色过渡的变量,你需要控制每帧的时间。让我给你一个快速和非常基本的例子,这样你就明白了。风格见谅...

#include <SFML/Graphics.hpp>

int main(){
  sf::RenderWindow renderWindow(sf::VideoMode(800, 600), "Color Animation");

  sf::Clock clock;
  sf::Event event;
  // Change to start the animation
  // Red and blue to store the color transition
  // Duration to control animation speed
  int change = 0;
  int red = 255;
  int blue = 0;
  float duration = float();

  // Set a basic red circle as the starting shape
  sf::Color color = sf::Color::Red;
  sf::CircleShape circle(150);
  circle.setFillColor(color);

  while (renderWindow.isOpen()){
    // How much time since last loop?
    sf::Time dt = clock.restart();
    duration += dt.asSeconds();

    while (renderWindow.pollEvent(event)){
      //Handle events here
      if (event.type == sf::Event::EventType::Closed)
        renderWindow.close();

      //Respond to key pressed events
      if (event.type == sf::Event::EventType::KeyPressed){
        if (event.key.code == sf::Keyboard::C){
          // C key pressed, start animation
          change = 1;
        }
      }
    }

    // Animation started and animation duration per frame (0.01f) reached
    // Change color by 1 
    if (change == 1 && duration > 0.01f){
      red -= 1;
      blue += 1;
      if (red > 0){
        // Reset frame time and set new color for circle
        duration = 0;
        color = sf::Color(red, 0, blue);
        circle.setFillColor(color);
      } else {
        // Stop animation 
        change = 0;
      }
    }

    // Clear render window and draw circle
    renderWindow.clear(sf::Color::Black);
    renderWindow.draw(circle);
    renderWindow.display();
  }
}