【问题标题】:cache sprites to save the memory缓存精灵以节省内存
【发布时间】:2012-04-18 23:08:22
【问题描述】:

在我的游戏场景中,我在 CCParallaxNode 中使用了 5 个背景图像(精灵),我必须使用每个精灵两次来永久移动所有这些图层。如何缓存这些精灵以节省内存?

我只想逃离 CCSprite *for _level_1CCSprite *for _level_2 因为它两次是同一张图片。

_backgroundNode = [CCParallaxNode node];
_backgroundNode.anchorPoint = CGPointMake(0, 0);
_backgroundNode.position = CGPointMake(0, 0);
[self addChild:_backgroundNode z:-1];

.....

循环中

            CCSprite *fon_level_1 = [CCSprite spriteWithFile:[NSString stringWithFormat:@"%@", name]];
            CCSprite *fon_level_2 = [CCSprite spriteWithFile:[NSString stringWithFormat:@"%@", name]];
            fon_level_1.anchorPoint = CGPointMake(0, 0);
            fon_level_1.position = CGPointMake(0, 0);
            fon_level_2.anchorPoint = CGPointMake(0, 0);
            fon_level_2.position = CGPointMake(0, 0);
            [_backgroundNode addChild:fon_level_1 z:zIndex parallaxRatio:ccp(ratio, ratio) positionOffset:ccp(offsetx, offsety*screenSize.height)];
            [_backgroundNode addChild:fon_level_2 z:zIndex parallaxRatio:ccp(ratio, ratio) positionOffset:ccp(fon_level_1.contentSize.width, offsety*screenSize.height)];
            [_backgrounds addObject:fon_level_1];
            [_backgrounds addObject:fon_level_2];

方法,移动 fons 并检查实现背景层的结束

-(void) updateBackgroud:(ccTime)delta
{
    CGPoint backgroundScrollVel = ccp(-1000, 0);

    _backgroundNode.position = ccpAdd(_backgroundNode.position, ccpMult(backgroundScrollVel, delta));

    for (CCSprite *background in _backgrounds) {
        if (([_backgroundNode convertToWorldSpace:background.position].x+background.contentSize.width/10) < -(background.contentSize.width)) {
            [_backgroundNode incrementOffset:ccp(background.contentSize.width*2,0) forChild:background];
        }
    }
}

【问题讨论】:

    标签: caching cocos2d-iphone sprite


    【解决方案1】:

    您应该只将纹理添加到纹理缓存一次,CCSprite 实例不会复制纹理。它只存储一个指向纹理和帧参数(原点和大小)的指针,以了解要使用纹理的哪一部分(例如,如果您有一个包含大量精灵的大图集)。

    实际上,您可能不会直接将纹理添加到纹理缓存中。它将被添加到 CCSprite 实例 init 方法中的纹理缓存中。

    【讨论】:

    • 例子? O_o CCSprite* sprite = [CCSprite spriteWithFile: filePath];在这行代码之后,您的纹理将被加载到纹理缓存中,下一个精灵实例实例将在纹理缓存中找到该纹理并使用它而不是创建纹理副本
    • CCTexture2D* tex = [[CCTextureCache sharedTextureCache] addImage:[NSString stringWithFormat:@"%@", name]]; CCSprite *fon_level_1 = [CCSprite spriteWithTexture:tex]; CCSprite *fon_level_2 = [CCSprite spriteWithTexture:tex];
    • 或者额外的,只是两次 CCSprite *fon_level_1 = [CCSprite spriteWithFile:[NSString stringWithFormat:@"%@", name]];?
    • 您可以将 sprite 与文件一起使用。一切都会好起来的。我更喜欢避免 spriteWithTexture 构造函数。如果您将精灵打包在一个大图集中(例如,2048x2048 像素),您将获得具有整个巨大纹理的精灵
    猜你喜欢
    • 2012-09-06
    • 1970-01-01
    • 1970-01-01
    • 2010-11-05
    • 2013-10-30
    • 2013-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多