0
我創建了一個名爲的SKSpriteNode
Obstacle
子類,並在init
實現物理體:SKPhysicsBody的malloc錯誤
-(id)initWithHeight:(NSInteger)height flipped:(BOOL)flipped
{
if (self = [super initWithImageNamed: @"obstacle.png"])
{
[self setName: @"obstacle"];
[self setSize: CGSizeMake(OBSTACLE_WIDTH, height)];
[self setPosition: CGPointZero];
// rotate if needed
if (flipped)
{
[self runAction: [SKAction rotateByAngle: 3.14 duration: 0.0f]];
}
// physics
SKPhysicsBody* pb = [SKPhysicsBody bodyWithRectangleOfSize: self.size];
pb.dynamic = NO;
pb.affectedByGravity = NO;
[pb setCategoryBitMask: obstacleCategory];
[pb setContactTestBitMask: playerCategory];
[self setPhysicsBody: pb];
}
return self;
}
然後在我的場景我有一次曾經幾秒鐘產卵2個障礙的方法。
Obstacle *ob0 = [[Obstacle alloc] initWithHeight: h0 flipped: NO];
[bottom setPosition: CGPointMake(x0, y0)];
Obstacle *ob1 = [[Obstacle alloc] initWithHeight: h1 flipped: YES];
[top setPosition: CGPointMake(x1, y1)];
NSArray* objs = @[ob0, ob1];
for (Obstacle* o in objs)
{
[self addChild: o];
[o runAction: [SKAction
moveToX: -OBSTACLE_WIDTH duration: SPAWN_SPEED*2]
completion:^{
[o removeFromParent];
}];
}
一段隨機時間(幾秒鐘,幾分鐘之間)運行後,應用程序將與
malloc: *** error for object 0x16553120: pointer being freed was not allocated
崩潰的錯誤被第一塊扔到下面的行代碼
SKPhysicsBody* pb = [SKPhysicsBody bodyWithRectangleOfSize: self.size];
我已經試過移動的物理實現了子類和到現場Obstacle
實例化後,卻拋出了同樣的錯誤。
編輯:
調試器給了我新的認識到我的問題:
*** Terminating app due to uncaught exception 'Cant add body,
already exists in a world', reason: 'Cant add body <SKPhysicsBody>
type:<Rectangle> representedObject:[<SKSpriteNode> name:'obstacle'
texture:[<SKTexture> 'obstacle.png' (50 x 200)] position:{400, 446}
size:{50, 244} rotation:0.00], already exists in a world'
做SKPhysicsNode
的需要有一個獨特的名字,也許?