鼠标点击后爆炸的sfml动画

sfml animation of explosion after mouseclick

本文关键字:sfml 动画 鼠标      更新时间:2023-10-16

我需要你的建议。我使用的是SFML,在鼠标点击事件后,我需要从精灵表中播放动画(例如64帧和每帧的40px宽/高)。我想到的唯一解决方案是:

if (event.type == sf::Event::MouseButtonPressed) {
                if (event.key.code == sf::Mouse::Left) {
                    float frame = 0;
                    float frameCount = 64;
                    float animSpeed = 0.005;
                    while (frame < frameCount) {
                        spriteAnimation->setTextureRect(sf::IntRect(int(frame)*w, 0, w, w));
                        frame += animSpeed;
                        window->draw(rect); // clear the area of displaying animation
                        window->draw(*spriteAnimation);
                        window->display();
                    }
                    ...

但是多次调用window->display()确实不好;你能提出更好的变体吗?

与其将动画的所有代码都干扰到事件块中,不如将其展开。

这里的设计非常不灵活,因为如果您想要显示动画以外的任何内容,则必须在事件循环之外再次调用window->display()

一般来说,在SFML中,你的游戏循环进行如下:

initialize();
while(running)
{
    checkEvents();
    clear();
    update();
    display();
}

与其执行所有的计算并在事件的if语句中显示动画,不如设置一个bool或调用某种doAnimation()函数

bool doAnimation = 0;
//declare frame, framespeed, etc
if (event.type == sf::Event::MouseButtonPressed) 
{
    if (event.key.code == sf::Mouse::Left) 
    {
        doAnimation = true; 
        //reset frame, framespeed, etc         
    }
}
clear();
if(doAnimation)
{
    sprite->setTexture(...);
    if(frame == endFrame)
    {
        doAnimation = 0;   
    }
    drawSprite();
}
window->display();

有很多方法可以解决你的问题。我的例子没有我认为的那么灵活,但根据你的程序的需要,它可能会很好地工作。如果你想采取下一步行动,将动画移到某种类中,从长远来看,会让你的生活轻松很多。