使用对象数组对 SFML 进行动画处理

animation of sfml by using array of objects

本文关键字:动画 处理 SFML 对象 数组      更新时间:2023-10-16

如何使用此代码为精灵制作动画?我知道我应该添加延时什么,但是怎么做呢?我使用对象数组来快速变化。还是一种非理性的动画方式?

#include <SFML/Graphics.hpp>
#include <iostream>
using namespace std;
sf::RenderWindow window(sf::VideoMode(600, 400), "!!!");
void animation()
{
sf::Texture arrayOfTexture[9];
sf::Sprite imageOfLamp;
arrayOfTexture[0].loadFromFile("1.png");
arrayOfTexture[1].loadFromFile("2.png");
arrayOfTexture[2].loadFromFile("3.png");
arrayOfTexture[3].loadFromFile("4.png");
arrayOfTexture[4].loadFromFile("5.png");
arrayOfTexture[5].loadFromFile("6.png");
arrayOfTexture[6].loadFromFile("7.png");
arrayOfTexture[7].loadFromFile("8.png");
arrayOfTexture[8].loadFromFile("9.png");
for(;;)
{
for(int i= 0;i <=8;i++)
{
imageOfLamp.setTexture(arrayOfTexture[i]);
window.draw(imageOfLamp);
}
for(int i =8;i >=0;i--)
{
imageOfLamp.setTexture(arrayOfTexture[i]);
window.draw(imageOfLamp);
}
}
}

正如评论中所说。对于动画,您需要捕获时间。否则,您将无法计算每帧的持续时间。并且您需要将当前帧存储在变量中。我在下面的示例代码中做了一些注释。它不再是一个类,因为我认为我们在这里需要一个运行的代码块。

另一种选择是精灵表,请参阅 https://www.gamefromscratch.com/post/2015/10/26/SFML-CPP-Tutorial-Spritesheets-and-Animation.aspx 我可以用精灵表重写答案,但我想您想先了解动画的基本机制。请在对我的帖子的评论中指出这一点。

顺便说一句,如果您不习惯游戏循环,请查看 https://gafferongames.com/post/fix_your_timestep/

#include <SFML/Graphics.hpp>
int main(){
sf::RenderWindow renderWindow(sf::VideoMode(800, 600), "Color Animation");
// Duration to control animation speed
int currentFrame = 1;
float duration = float();
sf::Clock clock;
sf::Event event;
sf::Texture arrayOfTexture[9];
arrayOfTexture[0].loadFromFile("1.png");
arrayOfTexture[1].loadFromFile("2.png");
arrayOfTexture[2].loadFromFile("3.png");
arrayOfTexture[3].loadFromFile("4.png");
arrayOfTexture[4].loadFromFile("5.png");
arrayOfTexture[5].loadFromFile("6.png");
arrayOfTexture[6].loadFromFile("7.png");
arrayOfTexture[7].loadFromFile("8.png");
arrayOfTexture[8].loadFromFile("9.png");
// Assign basic texture to sprite
sf::Sprite imageOfLamp;
imageOfLamp.setTexture(arrayOfTexture[0]);
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();
}
// Animation duration per frame (0.1f) reached
if (duration > 0.1f){
// Restart calculation of the duration
duration = 0;
// Loop through the animation frames
if (currentFrame < 9){
currentFrame += 1;
} else {
// Start from first frame if last frame reached
currentFrame = 0;
}
imageOfLamp.setTexture(arrayOfTexture[currentFrame]);
}
// Clear render window and draw sprite
renderWindow.clear(sf::Color::Black);
renderWindow.draw(imageOfLamp);
renderWindow.display();
}
}