- (void)didBeginContact未被调用。思考?

时间:2014-01-29 15:07:07

标签: objective-c sprite sprite-kit skspritenode skphysicsbody

#import "collisionTestMyScene.h"
const static int nodeBitMask = 0x1 << 0;
const static int node1BitMask = 0x1 << 1;;

@implementation collisionTestMyScene

-(id)initWithSize:(CGSize)size {    
    if (self = [super initWithSize:size]) {
        /* Setup your scene here */
        self.physicsWorld.contactDelegate = self;
        w = 0;


            }
    return self;
}
-(void) didBeginContact:(SKPhysicsContact *)contact {
    NSLog(@"Contact Begin");

    if (contact.bodyA.categoryBitMask == nodeBitMask) {
        NSLog(@"Node is Body A");
    }
    if (contact.bodyA.categoryBitMask == node1BitMask) {
        NSLog(@"Node is Body B");
    }
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    /* Called when a touch begins */

    for (UITouch *touch in touches) {
        CGPoint location = [touch locationInNode:self];
        node = [SKSpriteNode spriteNodeWithImageNamed:@"block.jpg"];
        node.position = location;
        [node setScale:0.07];
        node.physicsBody.contactTestBitMask = node1BitMask;
        node.physicsBody.categoryBitMask = nodeBitMask;
        node.physicsBody.collisionBitMask = nodeBitMask;
        //node.physicsBody.collisionBitMask = 0;
        node1 = [SKSpriteNode spriteNodeWithImageNamed:@"block2.jpg"];
        node1.position = CGPointMake(200, 200);
        node1.physicsBody.categoryBitMask = node1BitMask;
        node1.physicsBody.contactTestBitMask = nodeBitMask;
        node1.physicsBody.collisionBitMask = node1BitMask;
        //node1.physicsBody.collisionBitMask = 0;
        [node1 setScale:0.07];


        [self addChild:node];
        [self addChild:node1];
        node.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:CGSizeMake(node.size.width, node.size.height)];
        node1.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:CGSizeMake(node1.size.width, node1.size.height)];
        SKAction *moveUp = [SKAction moveToX:100 duration:3];
        node1.physicsBody.affectedByGravity = NO;
        node.physicsBody.affectedByGravity = NO;
        [node1 runAction:moveUp];
        w = 1;

    }



}

从来没有NSLogging任何东西。我试过改变位掩码等等。 CGRectIntersects函数可以工作,但是不够准确。此外,这两个节点是完美的盒子形状。我能做错什么?提前谢谢!

1 个答案:

答案 0 :(得分:2)

这里的问题是位掩码。这两个节点属于不同的类别,接触和冲突组(位掩码)。因此,它们不会接触也不会发生碰撞,因为比特掩码与AND进行比较,并且仅当结果为非零时才会发生接触/碰撞。

简而言之,至少要将它们放在相同的接触位掩码中,以便接收didBeginContact条消息。