Мне нужно запустить несколько анимаций листов спрайтов, каждый из которых имеет сотни кадров. Я пробовал SpriteKit, а также Cocos2D, у каждого из которых были проблемы с памятью и временем загрузки процессора. Может ли кто-нибудь порекомендовать лучший способ сделать это с помощью Cocos2D, SpriteKit или любого другого метода, чтобы минимизировать использование процессора и предотвратить сбой приложения из-за перегрузки памяти.
Лучшая техника для воспроизведения (анимации) огромных листов спрайтов
comment
Возможно, вы можете попробовать SKVideoNode stackoverflow.com/a/30556711/3402095
- person Whirlwind   schedule 01.09.2015
comment
Он должен быть интерактивным, поэтому видео не вариант.
- person Simulator   schedule 01.09.2015
comment
@Simulator- В вашем вопросе не хватает содержания, и он слишком широк. Попробуйте сузить свой вопрос до конкретной проблемы и показать, что вы пробовали до сих пор.
- person sangony   schedule 01.09.2015
Ответы (1)
вы можете сделать это, используя свой собственный класс, расширив spriteNode, вот пример в задаче c
создайте новый класс касания коки, в котором ваш файл .h содержит
#import <SpriteKit/SpriteKit.h>
@interface multiSpriteAnimation : SKSpriteNode
{
}
//variables
//starting frame of animation
@property (nonatomic,strong) SKTexture *startingFrame;
//sprite which hold all animtion
@property (nonatomic,strong) SKSpriteNode *animatedSprite;
@property (nonatomic,strong) NSMutableDictionary *allAnimation;
@property (nonatomic,strong) NSMutableDictionary *allAnimationFrameRates;
@property (nonatomic,strong) NSMutableDictionary *animationList;
//function
@property (nonatomic,strong) SKAction *currentAction;
-(id) copyWithZone: (NSZone *) zone;
- (instancetype)initSpritesAnimation:(SKTexture*)startingFrame;
//add animation
-(void)addAnimation:(NSMutableArray*)frames frameRate:(float)time withKey:(NSString*)Key;
-(void)playAnimation:(NSString*)label withType:(NSString*)type;
//play animation with sound
-(void)playAnimation:(NSString*)label withType:(NSString*)type withSound:(NSString*)soundname loopRequired:(BOOL)loop;
//clear all sounds
-(void)clearAllsounds;
@end
и .m файл содержат
#import "multiSpriteAnimation.h"
@implementation multiSpriteAnimation
{
SKTexture *__startingFrame;
}
- (instancetype)initSpritesAnimation:(SKTexture*)startingFrame
{
self = [super init];
if (self) {
//init all animation dictionary
_animationList=[[NSMutableDictionary alloc] init];
_allAnimation=[[NSMutableDictionary alloc] init];
_allAnimationFrameRates=[[NSMutableDictionary alloc] init];
//draw first frame for the animation
__startingFrame=startingFrame;
_animatedSprite=[SKSpriteNode spriteNodeWithTexture:startingFrame];
_animatedSprite.anchorPoint=CGPointMake(0.5, 0.5);
[self addChild:_animatedSprite];
}
return self;
}
-(void)addAnimation:(NSMutableArray*)frames frameRate:(float)time withKey:(NSString*)Key
{
//add all animation only once for stable framerate
[_allAnimation setObject:frames forKey:Key];
[_allAnimationFrameRates setObject:[NSNumber numberWithFloat:1/time] forKey:Key];
}
-(void)playAnimation:(NSString*)label withType:(NSString*)type
{
//total frame to play animation
NSMutableArray *frames=[_allAnimation objectForKey:label];
//frame rate of a animation
float time=[[_allAnimationFrameRates objectForKey:label] floatValue];
SKAction *Animation = [SKAction animateWithTextures:frames timePerFrame:time resize:TRUE restore:TRUE];
//play in a loop
if([type isEqualToString:@"loop"])
{
_currentAction = [SKAction repeatActionForever:Animation ];
}
//play once with complete handler
else if([type isEqualToString:@"playonce"])
{
_currentAction=Animation;
}
[_animatedSprite runAction:_currentAction];
//only one hero have cap
}
//clear all sounds
-(void)clearAllsounds
{
[self removeActionForKey:@"sound"];
}
-(id) copyWithZone: (NSZone *) zone
{
multiSpriteAnimation *copy = [[[self class] allocWithZone:zone] initSpritesAnimation:__startingFrame];
return copy;
}
-(void)playSound:(NSString *)path withLoop:(BOOL)loop
{
SKAction *sound;
if(loop)
{
sound = [SKAction playSoundFileNamed:path waitForCompletion:YES];
[self runAction:[SKAction repeatActionForever:sound] withKey:@"sound"];
}
else
{
sound = [SKAction playSoundFileNamed:path waitForCompletion:NO];
[self runAction:sound withKey:@"sound"];
}
}
//play animation with sound
-(void)playAnimation:(NSString*)label withType:(NSString*)type withSound:(NSString*)soundname loopRequired:(BOOL)loop
{
//total frame to play animation
NSMutableArray *frames=[_allAnimation objectForKey:label];
//frame rate of a animation
float time=[[_allAnimationFrameRates objectForKey:label] floatValue];
SKAction *Animation = [SKAction animateWithTextures:frames timePerFrame:time resize:TRUE restore:TRUE];
//play in a loop
if([type isEqualToString:@"loop"])
{
_currentAction = [SKAction repeatActionForever:Animation ];
[self playSound:soundname withLoop:loop];
}
//play once with complete handler
else if([type isEqualToString:@"playonce"])
{
_currentAction=Animation;
[self playSound:soundname withLoop:loop];
}
[_animatedSprite runAction:_currentAction];
//only one hero have cap
}
@end
теперь импортируйте этот класс в любую вашу сцену и добавляйте всю свою анимацию одну за другой
multiSpriteAnimation *player=[[multiSpriteAnimation alloc] initSpritesAnimation:A1[0]];
//where A1[0] is first frame of your animation
//and A1 as a array of frames or textures with a key
[player addAnimation:A1 frameRate:30.0f withKey:@"run"];
player.position=CGPointMake(200.0f, 400.0f);
[self addChild:player];
//play animation by key
[player playAnimation:@"run" withType:@"loop"];
this way you can handle multiple animation remember save all animation frames or textures as a singleton for further use
person
dragoneye
schedule
01.09.2015
он по-прежнему не разрешает пиковую нагрузку процессора в течение 10-15 секунд изначально, я добавляю 19 узлов, и каждый узел имеет около 40 кадров.
- person Simulator; 02.09.2015
Вы предварительно загружаете текстуры для анимации, пожалуйста, извлеките текстуры из атласа и предварительно загрузите их для дальнейшего использования, например. загрузить текстуру из атласа и сохранить их в классе данных или одноэлементном классе... поэтому вы загружаете атлас текстур в память для дальнейшего использования
- person dragoneye; 02.09.2015
Вы можете скачать код с здесь
- person Simulator; 03.09.2015