未检测到SpriteKit冲突

时间:2014-05-03 08:28:20

标签: ios sprite-kit

我的场景中有2个SKSpriteNodes,我想检测它们之间的碰撞。但是这不起作用。 这是相关代码

节点1:

 PSCarNode *newCar = [PSCarNode new];
newCar.size = CGSizeMake(CAR_WIDTH, CAR_HEIGHT);
CGFloat carXval =  - CAR_WIDTH; // start off-screen
newCar.position = CGPointMake(carXval, Yval);
newCar.zPosition = 5;
newCar.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:CGSizeMake(CAR_WIDTH, CAR_HEIGHT)];
newCar.physicsBody.dynamic = YES;
newCar.physicsBody.categoryBitMask = carCategory;
newCar.physicsBody.contactTestBitMask = frogCategory;
newCar.physicsBody.collisionBitMask  = 0;
newCar.physicsBody.usesPreciseCollisionDetection = YES;
[self addChild:newCar];

节点2:

    player = [[PSPLAYERNode alloc] init];
[player setPosition: CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame))];
[player setSize:CGSizeMake(PLAYER_SIZE, PLAYER_SIZE)];
player.zPosition = 1;
player.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:(3/4)*PLAYER_SIZE];
player.physicsBody.dynamic = YES;
player.physicsBody.collisionBitMask = 1;
player.physicsBody.categoryBitMask = playerCategory;
player.physicsBody.contactTestBitMask = carCategory;
[self addChild:player];

INIT:

    - (instancetype)initWithSize:(CGSize)size
{
    self = [super initWithSize:size];
    if (self) {
        [self createScene];
        self.physicsWorld.gravity = CGVectorMake(0., 0.); // no gravity
        self.physicsWorld.contactDelegate = self;
        animationInProgress = NO;
    }
    return self;
}

和委托:

    - (void)didBeginContact:(SKPhysicsContact *)contact
{
    NSLog(@"player hit");
}

为什么没有检测到碰撞。我可以清楚地看到汽车节点在玩家节点上移动,但日志中没有显示任何内容。

1 个答案:

答案 0 :(得分:1)

因为这两个对象分为两个不同的类别,它们的联系位掩码也会导致0。

根本没有设置位掩码,直到你真正需要它们来定义两个(一组)主体根本不应该接触或者应该生成接触事件但不解决冲突(即允许它们通过)的行为通过彼此)。

您可以找到有关位掩码在SKPhysicsBody class reference中的工作原理的信息。