CCPhysicsBody 碰撞在 cocos2d-swift v3.4 中不起作用

CCPhysicsBody Collision not working in cocos2d-swift v3.4

代码如下:

@interface MainScene : CCNode<CCPhysicsCollisionDelegate>

//.m

-(void)onEnter
{
    [super onEnter];

    mPhysicsWorld = [CCPhysicsNode node];
    mPhysicsWorld.gravity = ccp(0,0);

    mPhysicsWorld.debugDraw = YES;
    mPhysicsWorld.collisionDelegate = self;

    [self addChild:mPhysicsWorld];

    //Body_A
    {
        CCSprite *sprite = [CCSprite spriteWithImageNamed:@"sprite_1.png"];
        sprite.position = ccp(280, 220);
        sprite.rotation = 13;
        sprite.name = @"Body_A";
        sprite.physicsBody.collisionGroup=@"Group1";
        sprite.physicsBody.collisionType=@"typeA";
        CGRect rect = {CGPointZero, sprite.contentSize};
        CCPhysicsBody *body = sprite.physicsBody = [CCPhysicsBody bodyWithRect:rect cornerRadius:0.0];
        body.velocity = ccp(1000, 2000);
        body.angularVelocity = 1.0;
        body.type = CCPhysicsBodyTypeDynamic;

        [mPhysicsWorld addChild:sprite];
    }

    //Body_B
    {
        CCSprite *sprite = [CCSprite spriteWithImageNamed:@"sprite_2.png"];
        sprite.position = ccp(380, 220);
        sprite.rotation = 13;
        sprite.name = @"Body_B";
        sprite.physicsBody.collisionGroup=@"Group2";
        sprite.physicsBody.collisionType=@"typeB";
        CGSize size = sprite.contentSize;
        CGPoint points[] = {
            ccp(0, 0),
            ccp(size.width, 0),
            ccp(size.width/2, size.height),
        };

        CCPhysicsBody *body = sprite.physicsBody = [CCPhysicsBody bodyWithPolygonFromPoints:points count:3 cornerRadius:0.0];
        body.velocity = ccp(1000, -1000);
        body.angularVelocity = -1.0;
        body.type = CCPhysicsBodyTypeDynamic;

        [mPhysicsWorld addChild:sprite];
    }

//委托方法

- (BOOL)ccPhysicsCollisionBegin:(CCPhysicsCollisionPair *)pair typeA:(CCNode *)nodeA typeB:(CCNode *)nodeB
{
    printf("Function Called\n"); //control not coming here
    if([nodeA.name isEqualToString:@"Body_A"] &&  [nodeB.name isEqualToString:@"Body_B"])
    {
        return YES;
    }

    return NO;
}

类似问题:已经尝试this similar post但没有得到解决方案。

你可能要去 'palm-forehead' ,我也花了一段时间:(

对于正文 A 和正文 B,下面两行

sprite.physicsBody.collisionGroup=@"Group1";
sprite.physicsBody.collisionType=@"typeA";

在 physicsBody 仍为 nil 时执行。移动行下的行:

CCPhysicsBody *body = sprite.physicsBody = [CCPhysicsBody bodyWithRect:rect cornerRadius:0.0];

引用。经过测试和验证,适用于 SIM 卡和设备。祝你的项目好运。