在 Cocos2dx 中加载动画中使用的相同 SpriteFrame 时速度变慢

Slowdown when loading the same SpriteFrame used in an animation in Cocos2dx

我的游戏目前遇到了严重的速度下降问题。我已将其缩小到与纹理动画相关的内容。

在我的游戏中,角色会朝 4 个可能方向中的 1 个方向行走,他们会走到一个点,然后改变方向并继续行走(有点像塔防游戏)。

首先我像这样加载精灵帧缓存

SpriteFrameCache::getInstance()->addSpriteFramesWithFile("characters.plist");

此代码在我的应用程序生命周期内仅 运行 一次。

当角色加载到屏幕上时,将使用以下代码设置其动画:

int direction = 0;
int number = 0;

if (this->to_x < 0) // Left
{
    direction = 1;
    number = 1;
}
else if(this->to_x > 0) // Right
{
    direction = 2;
    number = 1;
}

if (this->to_y < 0) // Down
{
    direction = 0;
    number = 0;
}
else if(this->to_y > 0) // Up
{   
    direction = 3;
    number = 2;
}

int s = 0; //skin


// Set the animation
Animation *animation = Animation::create();

for (int i = 0; i < INT16_MAX; i++)
{
    string frame_sprite_name = StringUtils::format("%s_%d_%d_%d.png",parameters[name].image_name.c_str(),s,number,i);

    auto frame = SpriteFrameCache::getInstance()->getSpriteFrameByName(frame_sprite_name);

    if (frame) {
        animation->addSpriteFrame(frame);
    } else {
        break;
    }
}

// Invert the sprite when they go right
if (direction == 2) {
    setFlippedX(true);
}else{
    setFlippedX(false);
}

// Set the pace of the animation based on the type
if (name=="runner") {
    animation->setDelayPerUnit(0.15f);
} else{
    animation->setDelayPerUnit(0.3f);
}

Animate *animate = Animate::create(animation);
this->stopAllActions();
this->runAction(RepeatForever::create(animate));

这段代码的作用是:

  1. 检查方向
  2. 根据方向从缓存中获取精灵帧
  3. 运行永远重复的动作。

然而这段代码是 运行 每次他们改变方向来设置活动角色的新动画。另外,我一次可以让大约 40-50 个这样的角色四处走动。

我注意到在游戏中几分钟后,一旦创建了新的 "character",速度就会开始下降(因为它们是在波浪中快速连续创建的)。当角色改变方向时也会发生减速。所以这让我相信我使用的纹理是错误的。

如果有人知道如何解决这个问题,请告诉我。

PD:我在考虑预加载所有动画的可能性,然后让每个代表角色的 sprite 运行 对应的动画。

您绝对应该使用 addAnimationgetAnimation 方法将动画缓存在 AnimationCache 中。