我在我的应用程序中使用sprite kit进行物理和碰撞检测。
我有一些球落入一个盒子里。框的内部使用bodyWithPolygonFromPath
定义我将一些球放入盒子里然后直接掉进去。
以下是定义框
的代码SKSpriteNode* boxFront = [SKSpriteNode spriteNodeWithImageNamed: [boxData objectForKey: @"box_image"]];
boxFront.position = CGPointMake(0, -screenHeight*0.22);
boxFront.zPosition = 10;
[self addChild: boxFront];
CGFloat offsetX = boxFront.frame.size.width * boxFront.anchorPoint.x;
CGFloat offsetY = boxFront.frame.size.height * boxFront.anchorPoint.y;
CGMutablePathRef path = CGPathCreateMutable();
CGPathMoveToPoint(path, NULL, 3 - offsetX, 129 - offsetY);
CGPathAddLineToPoint(path, NULL, 0 - offsetX, 129 - offsetY);
CGPathAddLineToPoint(path, NULL, 0 - offsetX, 85 - offsetY);
CGPathAddLineToPoint(path, NULL, 200 - offsetX, 85 - offsetY);
CGPathAddLineToPoint(path, NULL, 200 - offsetX, 129 - offsetY);
CGPathAddLineToPoint(path, NULL, 197 - offsetX, 129 - offsetY);
CGPathAddLineToPoint(path, NULL, 196 - offsetX, 87 - offsetY);
CGPathAddLineToPoint(path, NULL, 3 - offsetX, 87 - offsetY);
CGPathCloseSubpath(path);
boxFront.physicsBody = [SKPhysicsBody bodyWithPolygonFromPath:path];
boxFront.physicsBody.dynamic = NO;
SKShapeNode* shape = [[SKShapeNode alloc] init];
shape.path = path;
shape.strokeColor = [UIColor redColor];
shape.zPosition = 101;
shape.lineWidth = 2;
[boxFront addChild: shape];
SKShapeNode的最后一位只是绘制了框的轮廓以进行调试。绘制的框是我期望碰撞框的位置。
这是我放入盒子里的球的代码。
SKSpriteNode* circle1 = [SKSpriteNode spriteNodeWithImageNamed: @"ball.png"];
circle1.position = CGPointMake(0, screenHeight*0.7);
circle1.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius: 20];
circle1.zPosition = 100;
[self addChild: circle1];
SKSpriteNode* circle2 = [SKSpriteNode spriteNodeWithImageNamed: @"ball.png"];
circle2.position = CGPointMake(-10, screenHeight);
circle2.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius: 20];
circle2.zPosition = 100;
[self addChild: circle2];
上面代码片段中的所有自我实例都是直接附加到SKScene的相同SKNode。
有关可能导致碰撞检测的原因的任何建议被忽略?
答案 0 :(得分:0)
我没有看到你宣布你的盒子或球的physicsBody.categoryBitMask
和physicsBody.collisionBitMask
属性。如果你没有为你的对象定义那些,你的代码将不知道哪些物理实体应该相互交互。