大家好,尝试在 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
然后在我的场景中,我在 interface
中声明了 playerNode
: 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 上运行
最佳答案
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 中声明一个方便的方法,以在单个步骤中分配/初始化。
编辑:
在 Ships.m 中声明类方法
+ (Ships *)shipNodeWithImageNamed:(NSString *)imageName
{
return [[Ships alloc] initWithImageNamed:imageName];
}
将方法原型(prototype)添加到 Ships.h
+ (Ships *)shipNodeWithImageNamed:(NSString *)imageName;
并创建一个新的船节点
playerNode = [Ships shipNodeWithImageNamed:@"Nova-L1"];
关于ios - Spritekit 子类节点显示为 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26594098/