我有一个NSArray,我用SKTexture填充动物跳跃动画:
@interface PSFrogNode ()
@property (strong, nonatomic) NSArray *leapFrames;
@end
@implementation PSFrogNode {
}
- (instancetype)init
{
self = [super init];
if (self) {
SKTextureAtlas *frogLeapAtlas = [SKTextureAtlas atlasNamed:kFrogLeapAtlas];
int numImages = frogLeapAtlas.textureNames.count;
NSMutableArray *tempArray = [NSMutableArray arrayWithCapacity:numImages];
for (int i=1; i <= numImages/2; i++) {
NSString *textureName = [NSString stringWithFormat:@"frogLeap%d", i];
SKTexture *temp = [frogLeapAtlas textureNamed:textureName];
[tempArray addObject:temp];
}
self.leapFrames = [NSArray arrayWithArray:tempArray];
self = [PSFrogNode spriteNodeWithTexture:[self.leapFrames objectAtIndex:0]];
[self setUserInteractionEnabled:NO];
}
return self;
}
- (void)animateFrogLeap
{
[self runAction:[SKAction animateWithTextures:self.leapFrames timePerFrame:0.09 resize:NO restore:YES]];
}
数组self.leapFrames在init方法中分配,但是当场景调用animateFrogLeap方法时,它是空的(意思是nil)。 那是为什么?
答案 0 :(得分:1)
您想在init
方法之外创建数组,然后将其传递到:
创建视图时
SKTextureAtlas *frogLeapAtlas = [SKTextureAtlas atlasNamed:kFrogLeapAtlas];
int numImages = frogLeapAtlas.textureNames.count;
NSMutableArray *images = [NSMutableArray arrayWithCapacity:numImages];
for (int i=1; i <= numImages/2; i++) {
NSString *textureName = [NSString stringWithFormat:@"frogLeap%d", i];
SKTexture *temp = [frogLeapAtlas textureNamed:textureName];
[images addObject:temp];
}
PSFrogNode *node = [[PSFrogNode alloc] initWithImages:images];
// Now use the node
<强> PSFrogNode.h 强>
-(instancetype)initWithImages:(NSArray *)images;
<强> PSFrogNode.m 强>
@interface PSFrogNode ()
@property (nonatomic, copy) NSArray *leapFrames;
@end
@implementation PSFrogNode
-(instancetype)initWithImages:(NSArray *)images
{
self = [self initWithTexture:[images firstObject]];
if (self) {
_leapFrames = [images copy];
[self setUserInteractionEnabled:NO];
}
return self;
}
正如我的评论中所提到的,原始实现中的下一行将意味着self
将被重新分配,因此它之前的行(将数组分配给属性)将意味着更少。
self = [PSFrogNode spriteNodeWithTexture:[self.leapFrames objectAtIndex:0]];