碰撞检测在SpriteKit中不起作用

时间:2014-12-17 04:40:07

标签: objective-c sprite-kit

我现在被困在这几个小时,这似乎是一项非常简单的任务。我有一个SKSpriteNode调用Ball,它在下面声明:

-(instancetype) initWithType:(BallType) ballType
{
    if(ballType == UserBall) {

        self = [super initWithImageNamed:USER_BALL_IMAGE];
        self.physicsBody.categoryBitMask = BBPhysicsCategoryUserBall;
        self.physicsBody.contactTestBitMask = BBPhysicsCategoryRedBall | BBPhysicsCategoryWorld;
        self.physicsBody.collisionBitMask = 0;
    }

    // setup physical aspects of the ball
    self.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:self.size.width/2];
    self.physicsBody.friction = 0.0f;
    self.physicsBody.dynamic = YES;

    return self;

}

我创建了另一个SKSpriteNote“redBall”,如下所示:

  SKSpriteNode *redBall = [[SKSpriteNode alloc] initWithImageNamed:RED_BALL_IMAGE];
        redBall.physicsBody.categoryBitMask = BBPhysicsCategoryRedBall;
        redBall.physicsBody.contactTestBitMask = BBPhysicsCategoryUserBall;
        redBall.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:redBall.size.width/2];
        redBall.physicsBody.friction = 0.0f;

        redBall.position = CGPointMake(self.size.width/2 , self.size.height/4);

        [self addChild:redBall];

        [redBall.physicsBody applyImpulse:CGVectorMake(0.0, 0.5)];

我的GameScene继承自SKScene并实施SKPhysicsContactDelegate协议。我按如下方式分配contactDelegate:

-(void) setupPhysicsWorld {

    self.physicsBody = [SKPhysicsBody bodyWithEdgeLoopFromRect:self.frame];
    self.physicsWorld.gravity = CGVectorMake(0.0f, 0.0f);
    self.physicsBody.friction = 0.0f;

    self.physicsBody.categoryBitMask = BBPhysicsCategoryWorld;
    self.physicsWorld.contactDelegate = self;

}

但由于某种原因,didBeginContact永远不会被打电话!我为什么不被召唤而疯了?

1 个答案:

答案 0 :(得分:0)

-(instancetype) initWithType:(BallType) ballType
{
    if(ballType == UserBall) {

        self = [super initWithImageNamed:USER_BALL_IMAGE];
        self.physicsBody.categoryBitMask = BBPhysicsCategoryUserBall;
        self.physicsBody.contactTestBitMask = BBPhysicsCategoryWorld;
        self.physicsBody.collisionBitMask = 0;
    }

    // setup physical aspects of the ball
    self.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:self.size.width/2];
    self.physicsBody.friction = 0.0f;
    self.physicsBody.dynamic = YES;

    return self;

}

  SKSpriteNode *redBall = [[SKSpriteNode alloc] initWithImageNamed:RED_BALL_IMAGE];
        redBall.physicsBody.categoryBitMask = BBPhysicsCategoryRedBall;
        redBall.physicsBody.contactTestBitMask = BBPhysicsCategoryUserBall;
        redBall.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:redBall.size.width/2];
        redBall.physicsBody.friction = 0.0f;

        redBall.position = CGPointMake(self.size.width/2 , self.size.height/4);

        [self addChild:redBall];

        [redBall.physicsBody applyImpulse:CGVectorMake(0.0, 0.5)];
 you are setting  redBall.physicsBody.contactTestBitMask  twice