didBeginContact :( SKPhysicsContact *)联系人未被调用

时间:2013-10-30 07:11:22

标签: ios objective-c xcode ios7

我创建了SKScene继承的类。 问题是关于物理体方法的接触

- (void)didBeginContact:(SKPhysicsContact *)contact 

未被调用 解决方案可能很简单,但作为精灵套件的初学者我坚持这个。

以下是代码

#import "MyScene.h"
@interface MyScene ()
@property BOOL contentCreated;
@end
@implementation MyScene
- (id)initWithSize:(CGSize)size {
    self = [super initWithSize:size];
    if (self) {
        self.physicsWorld.contactDelegate = self;
        self.physicsBody = [SKPhysicsBody bodyWithEdgeLoopFromRect:self.frame];
    }
    return self;
}
- (void)didMoveToView:(SKView *)view
{
    if (!self.contentCreated) {
        [self buildWorld];
        self.physicsWorld.contactDelegate = self;
    }
}

#pragma mark - World Building
- (void)buildWorld {
    NSLog(@"Building the world");
    SKSpriteNode * sprite1 = [[SKSpriteNode alloc] initWithColor:[SKColor grayColor] size:CGSizeMake(100,100)];
    sprite1.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:CGSizeMake(100,100)];
    sprite1.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame) +100);

    SKSpriteNode * sprite2 = [[SKSpriteNode alloc] initWithColor:[SKColor grayColor] size:CGSizeMake(100,100)];
    sprite2.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:CGSizeMake(100,100)];
    sprite2.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame) - 100);


    [self addChild:sprite1];
    [self addChild:sprite2];
}
- (void)didBeginContact:(SKPhysicsContact *)contact
{
    NSLog(@"contact");
}

@end

提前致谢。

1 个答案:

答案 0 :(得分:13)

来自SKPhysicsWorld文档:

  

当两个物理实体重叠时,会创建一个联系人   物理实体具有与contactTestBitMask重叠的categoryBitMask属性   另一个人的categoryBitMask财产。

您必须为物理机构分配contactTestBitMaskstatic const uint32_t sprite1Category = 0x1 << 0; static const uint32_t sprite2Category = 0x1 << 1; 。您想先创建类别:

sprite1.physicsBody.categoryBitMask = sprite1Category;
sprite1.physicsBody.contactTestBitMask = sprite2Category;

sprite2.physicsBody.categoryBitMask = sprite2Category;
sprite2.physicsBody.contactTestBitMask = sprite1Category;

接下来,分配类别和联系测试位掩码:

SKPhysicsBody

请注意{{1}}文档:

  

为获得最佳性能,仅设置触点掩码中的位   您感兴趣的互动。

相关问题