Spritekit Subclassed节点显示为nil

时间:2014-10-27 18:13:52

标签: ios objective-c sprite-kit subclassing skspritenode

Heyo伙计们,在SpriteKit中尝试创建子类节点时遇到了一个奇怪的问题。我在编译时没有错误,应用程序运行直到我进入需要添加节点作为场景的子节点的地方,然后失败并说reason: 'Attemped to add nil node to parent:我不确定我是什么失踪,任何帮助表示赞赏!这是我的节点标题:

#import <SpriteKit/SpriteKit.h>

@interface Ships : SKSpriteNode

-(Ships *)initWithImageNamed: (NSString *)imageName;

@end

以下是实施:

#import "Ships.h"

@implementation Ships

-(Ships *)initWithImageNamed: (NSString *)imageName
{
self = [Ships spriteNodeWithImageNamed:imageName];

// Adds more accurate physics body for ship collisions
CGFloat offsetX = (self.frame.size.width * 1.2) * self.anchorPoint.x;
CGFloat offsetY = (self.frame.size.height * 1.2) * self.anchorPoint.y;

CGMutablePathRef path = CGPathCreateMutable();

CGPathMoveToPoint(path, NULL, 8 - offsetX, 30 - offsetY);
CGPathAddLineToPoint(path, NULL, 7 - offsetX, 22 - offsetY);
CGPathAddLineToPoint(path, NULL, 50 - offsetX, 2 - offsetY);
CGPathAddLineToPoint(path, NULL, 65 - offsetX, 7 - offsetY);
CGPathAddLineToPoint(path, NULL, 70 - offsetX, 8 - offsetY);
CGPathAddLineToPoint(path, NULL, 27 - offsetX, 31 - offsetY);

CGPathCloseSubpath(path);

self.physicsBody = [SKPhysicsBody bodyWithPolygonFromPath:path];
self.physicsBody.dynamic = NO;
self.physicsBody.restitution = 0.0f;
self.physicsBody.friction = 0.0f;
self.physicsBody.linearDamping = 1.0f;
self.physicsBody.allowsRotation = NO;
self.physicsBody.usesPreciseCollisionDetection = YES;

// Keeps player ship on top of all other objects(unless other objects are assigned greater z position
self.zPosition = 100.0f;

return self;
}

@end

然后在我的场景中,我在playerNode中使用interface声明Ships *playerNode;,并尝试实现该节点的方法:

-(void) createPlayerNode
{
playerNode = [playerNode initWithImageNamed:@"Nova-L1"];
playerNode.position = CGPointMake(self.frame.size.width/5, self.frame.size.height/2);
playerNode.physicsBody.categoryBitMask = CollisionCategoryPlayer;
playerNode.physicsBody.collisionBitMask = 0;
playerNode.physicsBody.contactTestBitMask = CollisionCategoryBottom | CollisionCategoryObject | CollisionCategoryScore | CollisionCategoryPup;

[self addChild:playerNode];
}

我在应用程序的其他位置调用了[self createPlayerNode];,并且我尽快...崩溃。任何帮助是极大的赞赏!另外,我在iPhone 5上运行

1 个答案:

答案 0 :(得分:2)

Ships的初始化程序是一个实例方法而不是类方法,所以你的alloc / init语句应该是

playerNode = [[Ships alloc] initWithImageNamed:@"Nova-L1"]];

并在Ships.m中,替换

self = [Ships spriteNodeWithImageNamed:imageName];

用这个

self = [super initWithImageNamed:imageName];

此外,您应该在创建物理实体后释放路径......

    ship.physicsBody = [SKPhysicsBody bodyWithPolygonFromPath:path];

    CGPathRelease(path);

或者,您可以在Ships.m中声明一个方便的方法来一步分配/ init。

修改

在Ships.m中声明类方法

+ (Ships *)shipNodeWithImageNamed:(NSString *)imageName
{
    return [[Ships alloc] initWithImageNamed:imageName];
}

将方法原型添加到Ships.h

+ (Ships *)shipNodeWithImageNamed:(NSString *)imageName;

并通过

创建一个新的船舶节点
playerNode = [Ships shipNodeWithImageNamed:@"Nova-L1"];