SKPhysicsBody malloc error

大城市里の小女人 提交于 2019-12-12 04:59:52

问题


I created a subclass called Obstacle of SKSpriteNode and implement the physics body in the init:

-(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;
}

Then in my scene I have a method that spawns 2 obstacles at a time ever couple of seconds.

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];
           }];
}

After running for a random period of time (between a few seconds and a few minutes), the app will crash with

malloc: *** error for object 0x16553120: pointer being freed was not allocated

The error gets thrown on the following line in the first chunk of code

SKPhysicsBody* pb = [SKPhysicsBody bodyWithRectangleOfSize: self.size];

I've tried moving the physics implementation out of the subclass and into the scene after the Obstacle is instantiated, but it throws the same error.

Edit:

The debugger gave me new insight to my problem:

*** 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'

Do SKPhysicsNodes need to have a unique name maybe?


回答1:


I found the solution! Because I was generating a random number for hight and subtracting that number from the height of the view for the other obstacle, sometimes the height was a negative value which would cause the error in creating the physics body. I hope this helps someone else down the line, cause I was banging my head over it all day



来源:https://stackoverflow.com/questions/21745797/skphysicsbody-malloc-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!