我希望用户创建的每个spritenode
都带有左右边缘位掩码。其他位掩码工作,但这个没有。
创建新spritenode
的方法,在TouchesBegin
-(void)spawnBrick
{
brick = [[BrickNodeOne alloc] init];
brick.name = @"Brick";
NSArray *array = [self objectForKeyedSubscript:@"Brick"];
BrickNodeOne *oldBrick;
if ([array count] > 0) {
oldBrick = [array objectAtIndex:([array count]-1)];
}
brick.position = CGPointMake(brick.size.width / 2, (brick.size.height + oldBrick.position.y)-15);
brick.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:CGSizeMake(brick.size.width, brick.size.height)];
brick.physicsBody.categoryBitMask = kBrickCategory;
brick.physicsBody.contactTestBitMask = kCarCategory;
brick.physicsBody.collisionBitMask = 0;
[self addChild:brick];
SKAction *moveTo = [SKAction moveByX:0.0 y:-125.0 duration:1.0];
[brick runAction:[SKAction repeatActionForever:moveTo]withKey:@"moveDown"];
_brickRightEdge = [[SKNode alloc] init];
_brickRightEdge.physicsBody = [SKPhysicsBody bodyWithEdgeFromPoint:CGPointMake(brick.size.width, 0.0) toPoint:CGPointMake(brick.size.width, brick.size.height)];
_brickRightEdge.physicsBody.dynamic = NO;
_brickRightEdge.physicsBody.categoryBitMask = brickRightEdgeCategory;
_brickRightEdge.physicsBody.contactTestBitMask = kCarCategory;
_brickRightEdge.position = brick.position;
[brick addChild:_brickRightEdge];
_brickLeftEdge = [[SKNode alloc] init];
_brickLeftEdge.physicsBody = [SKPhysicsBody bodyWithEdgeFromPoint:CGPointMake(0.0, 0.0) toPoint:CGPointMake(0.0, brick.size.height)];
_brickLeftEdge.physicsBody.dynamic = NO;
_brickLeftEdge.position = brick.position;
_brickLeftEdge.physicsBody.categoryBitMask = brickLeftEdgeCategory;
_brickLeftEdge.physicsBody.contactTestBitMask = kCarCategory;
[brick addChild:_brickLeftEdge];
}
我希望用砖左右边缘进行碰撞检测的汽车spritenode
在didMoveToView
SKSpriteNode *car = [SKSpriteNode spriteNodeWithImageNamed:@"HighWayCar_Red"];
car.position = CGPointMake(self.size.width / 2, 120);
car.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:car.size];
car.physicsBody.categoryBitMask = kCarCategory;
car.physicsBody.contactTestBitMask = kWaterCategory | brickLeftEdgeCategory | brickRightEdgeCategory;
car.physicsBody.collisionBitMask = 0;
car.physicsBody.dynamic = NO;
car.zPosition = 2;
[self addChild:car];
代码DidBeginContact
if (firstBody.categoryBitMask == kCarCategory && secondBody.categoryBitMask == brickLeftEdgeCategory) {
NSLog(@"HIT");
}
if (firstBody.categoryBitMask == kCarCategory && secondBody.categoryBitMask == brickRightEdgeCategory) {
NSLog(@"HIT");
}
更新评论
I declared `SKPhysicsContactDelegate` in the header file. Set the delegate in `didMoveToView`
位掩码:
static const uint32_t kBrickCategory = 0x1 << 0;
static const uint32_t leftEdgeCategory = 0x1 << 1;
static const uint32_t rightEdgeCategory = 0x1 << 2;
static const uint32_t brickLeftEdgeCategory = 0x1 << 3;
static const uint32_t brickRightEdgeCategory = 0x1 << 4;
static const uint32_t kCarCategory = 0x1 << 5;
static const uint32_t kWaterCategory = 0x1 << 6;