我更喜欢接触处理。接触测试是在每一帧中完成的,就像更新的处理:。但是通过比较位(SKPhysicsBody.categoryBitMask)的接触检测非常快速和轻量级。
我需要检测并移除离开屏幕的球。因此,我设置了一个不可见的边框,因为场景物理体刚好足够大,可以检测到完全离开屏幕的球。
如果物理体。联系节点#1 的 TestBitMask == PhysicsBody。节点#2的类别BitMask然后是didBeginContact:当他们两个取得联系时被调用。
-(void)didMoveToView:(SKView *)view {
// bitmasks:
static uint32_t const categoryBitMaskBall = 0x1<<1;
static uint32_t const categoryBitMaskBorder = 0x1<<6;
CGFloat ballDiameter = [BallSprite radius] *2;
// floorShape is my scenes background
CGRect largeFloorFrame = floorShape.frame;
largeFloorFrame.origin.x -= ballDiameter;
largeFloorFrame.origin.y -= ballDiameter;
largeFloorFrame.size.width += ballDiameter *2;
largeFloorFrame.size.height += ballDiameter *2;
CGPathRef pathMainView = CGPathCreateWithRect(largeFloorFrame, nil);
self.physicsBody = [SKPhysicsBody bodyWithEdgeLoopFromPath:pathMainView];
self.physicsBody.categoryBitMask = categoryBitMaskBorder;
}
- (BallSprite*)addBall {
// initialize ball with additional configuration...
BallSprite *ball = [BallSprite ballAtPoint:(CGPoint)p];
ball.categoryBitMask = categoryBitMaskBall;
ball.contactTestBitMask = categoryBitMaskBorder;
[self addChild:ball];
}
- (void)didBeginContact:(SKPhysicsContact *)contact {
SKPhysicsBody *firstBody, *secondBody;
if (contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask) {
firstBody = contact.bodyA;
secondBody = contact.bodyB;
}
else {
firstBody = contact.bodyB;
secondBody = contact.bodyA;
}
/*!
Check on outside border contact
*/
if ((firstBody.categoryBitMask & categoryBitMaskBall) != 0 &&
(secondBody.categoryBitMask & categoryBitMaskBorder) != 0) {
[firstBody.node removeFromParent];
}
if ((firstBody.categoryBitMask & categoryBitMaskBorder) != 0 &&
(secondBody.categoryBitMask & categoryBitMaskBall) != 0) {
[secondBody.node removeFromParent];
}
}