知道为什么我的 didBeginContact 方法从不触发吗?球体和矩形实际上相互接触......
这里我声明了两个类别
static const uint32_t rectangleCategory = 0x1 << 0;
static const uint32_t ballCategory = 0x1 << 1;
这个方法创建一个球体
- (SKSpriteNode *)createSphereNode
{
SKSpriteNode *sphereNode =
[[SKSpriteNode alloc] initWithImageNamed:@"sphere.png"];
sphereNode.name = @"sphereNode";
sphereNode.physicsBody.categoryBitMask = ballCategory;
sphereNode.physicsBody.contactTestBitMask = rectangleCategory;
return sphereNode;
}
这个方法创建一个矩形
- (void) createRectangle
{
SKSpriteNode *rectangle = [[SKSpriteNode alloc] initWithImageNamed:@"balk.png"];
rectangle.position = CGPointMake(randomBetween(0, self.size.width),
self.size.height);
rectangle.name = @"rectangleNode";
rectangle.physicsBody =
[SKPhysicsBody bodyWithCircleOfRadius:(rectangle.size.width/2)-7];
rectangle.physicsBody.usesPreciseCollisionDetection = YES;
rectangle.physicsBody.categoryBitMask = rectangleCategory;
rectangle.physicsBody.contactTestBitMask = ballCategory;
[self addChild:rectangle];
}
这是不触发的 didBeginContact 方法
- (void) didBeginContact:(SKPhysicsContact *)contact
{
NSLog(@"Contact begin");
SKSpriteNode *firstNode, *secondNode;
firstNode = (SKSpriteNode *)contact.bodyA.node;
secondNode = (SKSpriteNode *) contact.bodyB.node;
if ((contact.bodyA.categoryBitMask == rectangleCategory)
&& (contact.bodyB.categoryBitMask == ballCategory))
{
CGPoint contactPoint = contact.contactPoint;
float contact_x = contactPoint.x;
float target_x = secondNode.position.x;
float margin = secondNode.frame.size.height/2 - 25;
if ((contact_x > (target_x - margin)) &&
(contact_x < (target_x + margin)))
{
NSLog(@"Hit");
self.score++;
}
}
}
有什么想法吗?非常感谢所有帮助!
提前致谢
静
最佳答案
我最初怀疑可能是缺少合适的 SKPhysicsContactDelegate,因为它在原始帖子中没有提到。然而,在检查代码时,情况并非如此,问题只是用于矩形的 SKPhysicsBody
是使用不合适的 bodyWithCircleOfRadius:
而不是 bodyWithRectangleOfSize:
.
rectangle.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize: rectangle.size];
原始答案,对于这种特殊情况不正确,但留在这里供有类似问题的任何人使用:
在您提供的代码中的任何地方都没有提到 SKPhysicsContactDelegate
。 didBeginContact:
方法是 SKScene
的 physicsWorld
属性的委托(delegate)方法。
因此,例如,如果您想让 SKScene
成为自己的委托(delegate),则它必须支持 SKPhysicsContactDelegate
协议(protocol)。 e.例如:
@interface YourSceneSubclass : NSObject <SKPhysicsContactDelegate>
然后您需要在游戏正确开始之前将代理设置在场景中的某个位置...
self.physicsWorld.contactDelegate = self;
关于ios - didBeginContact 不触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21834716/