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

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

本文关键字:SpriteFrame 速度 加载 Cocos2dx 动画      更新时间:2023-10-16

我目前在游戏中遇到了一些严重的减速。我已经将它缩小到与纹理动画相关的内容。

在我的游戏中,有一些角色沿着四个可能的方向中的一个走,他们会走到一个点,然后改变方向继续走(有点像塔防游戏)。

首先,我正在加载类似于的精灵帧缓存

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个这样的角色四处走动。

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

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

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

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