2013-10-30 73 views
9

我創建了SKScene繼承類。 問題是,在物理體的方法的接觸didBeginContact:(SKPhysicsContact *)contact not invoked

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

感謝。

+0

@Alexander他們確實倒下來互相碰觸 – raheem52

回答

13

SKPhysicsWorld文檔:

當兩個物理機構重疊和 物理機構之一具有contactTestBitMask性質與 其他機構的categoryBitMask財產重疊創建聯繫人。

您必須指定物理實體categoryBitMaskcontactTestBitMask。您需要先創建您的類別:

static 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文檔:

爲了獲得最佳性能,只在聯繫人掩碼中設置 您有興趣的互動位。