EXC_BAD_ACCESS SKPhysicsWorld

时间:2014-01-02 00:12:51

标签: ios ios7 xcode5 sprite-kit

我真的很困惑为什么我在[world addJoint:pinJoin];获得EXC_BAD_ACCESS(code = 1,address = 0x1c)。

JointTest.m

#import "JointTest.h"

@implementation JointTest
-(SKNode *)initWithWorld:(SKPhysicsWorld *)pWorld{
    if(self = [super init]){
       world = pWorld;
       [self attachBodies];
    }
    return self;
}
-(void)attachBodies{
    SKSpriteNode * spriteA = [[SKSpriteNode alloc]initWithImageNamed:@"rocket"];
    SKSpriteNode * spriteB = [[SKSpriteNode alloc]initWithImageNamed:@"rocket"];

    SKPhysicsBody * bodyA = [SKPhysicsBody bodyWithRectangleOfSize:spriteA.size];
    SKPhysicsBody * bodyB = [SKPhysicsBody bodyWithRectangleOfSize:spriteB.size];

    spriteA.position = CGPointMake(150, 300);
    spriteB.position = CGPointMake(150, 300 + spriteB.size.height/2);

    [self addChild:spriteA];
    [self addChild:spriteB];

    bodyA.dynamic = NO;

    spriteA.physicsBody = bodyA;
    spriteB.physicsBody = bodyB;

    SKPhysicsJointPin * pinJoin = [SKPhysicsJointPin jointWithBodyA:spriteA.physicsBody bodyB:spriteB.physicsBody anchor:spriteA.position];
    [world addJoint:pinJoin];

}
@end

JointTest.h

#import <SpriteKit/SpriteKit.h>

@interface JointTest : SKNode{
    SKPhysicsWorld * world;
}
-(SKNode *)initWithWorld:(SKPhysicsWorld *)pWorld;
@end

在SKScene中

JointTest * test = [[JointTest alloc]initWithWorld:self.physicsWorld];
[self addChild:test];

令我困惑的是将attachBodies方法中的代码移动到场景中并使用场景的physicsWorld调用addJoint方法效果很好。例如:

SKSpriteNode * spriteA = [[SKSpriteNode alloc]initWithImageNamed:@"rocket"];
SKSpriteNode * spriteB = [[SKSpriteNode alloc]initWithImageNamed:@"rocket"];

SKPhysicsBody * bodyA = [SKPhysicsBody bodyWithRectangleOfSize:spriteA.size];
SKPhysicsBody * bodyB = [SKPhysicsBody bodyWithRectangleOfSize:spriteB.size];

spriteA.position = CGPointMake(150, 300);
spriteB.position = CGPointMake(150, 300 + spriteB.size.height/2);

[self addChild:spriteA];
[self addChild:spriteB];

bodyA.dynamic = NO;

spriteA.physicsBody = bodyA;
spriteB.physicsBody = bodyB;

SKPhysicsJointPin * pinJoin = [SKPhysicsJointPin jointWithBodyA:spriteA.physicsBody bodyB:spriteB.physicsBody anchor:spriteA.position];
[self.physicsWorld addJoint:pinJoin];

我已经把头发拉了几个小时,所以如果有人有想法我会非常感激。谢谢!

1 个答案:

答案 0 :(得分:5)

在init上传递物理世界并不是一个好的设计。而是正常创建类的实例,然后从创建JointTest实例的任何位置向其发送attachBodies消息。然后你可以通过self.scene.physicsWorld访问物理世界,而不是必须通过世界并保持对它的无关参考。

而不是:

JointTest * test = [[JointTest alloc]initWithWorld:self.physicsWorld];
[self addChild:test];

这样做:

JointTest * test = [JointTest node];
[self addChild:test];
[test attachBodies];

请注意,attachBodies之后会发送addChild,因为在addChild之前,JointTest的scene属性仍为零。

我打赌这也可以解决你的问题,但这是一个猜测

您创建JointTest并立即添加两个带关节的精灵,但此时JointTest实例尚未添加到节点图中(通过addChild)。因此,JointTest及其两个子节点在开始时还没有与物理世界“注册”,这可能导致崩溃。