2013-10-30 15 views
9

Tôi đã tạo SKScene lớp kế thừa. Vấn đề là khi tiếp xúc của phương pháp cơ thể vật lýdidBeginLiên hệ: (SKPhysicsContact *) liên hệ không được gọi

- (void)didBeginContact:(SKPhysicsContact *)contact 

không gọi giải pháp có thể được đơn giản nhưng như người mới bắt đầu với bộ sprite tôi đang mắc kẹt với điều này.

Dưới đây là mã

#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 

Cảm ơn trước.

+0

@Alexander chúng rơi xuống để chạm vào nhau – raheem52

Trả lời

13

Từ các tài liệu SKPhysicsWorld:

Một tiếp xúc được tạo ra khi hai cơ quan vật lý chồng chéo lên nhau và một trong những cơ quan vật lý có một tài sản mà chồng chéo với tài sản categoryBitMask các cơ quan khác của contactTestBitMask.

Bạn phải chỉ định các vật lý vật lý là categoryBitMaskcontactTestBitMask. Bạn muốn đầu tiên tạo các danh mục của bạn:

static const uint32_t sprite1Category = 0x1 << 0; 
static const uint32_t sprite2Category = 0x1 << 1; 

Tiếp theo, gán các mặt nạ thử nghiệm chút thể loại và liên hệ:

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

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

Lưu ý từ các tài liệu SKPhysicsBody:

Đối với hiệu suất tốt nhất, chỉ có đặt các bit trong mặt nạ danh bạ cho các tương tác mà bạn quan tâm.

Các vấn đề liên quan