Detecting collisions in sprite kit

前端 未结 2 1889
清歌不尽
清歌不尽 2020-11-27 05:37

I\'m trying to make a simple game with sprite kit. The basic idea is that there is one player who can jump to avoid blocks. But i have a problem I don\'t know how to make it

2条回答
  •  一个人的身影
    2020-11-27 06:10

    The categoryBitMask sets the category that the sprite belongs to, whereas the collisionBitMask sets the category with which the sprite can collide with and not pass-through them.

    For collision detection, you need to set the contactTestBitMask. Here, you set the categories of sprites with which you want the contact delegates to be called upon contact.

    What you have already done is correct. Here are a few additions you need to do:

    _player.physicsBody.contactTestBitMask = blockCategory;
    _blok.physicsBody.contactTestBitMask = playerCategory;
    

    Afterwards, implement the contact delegate as follows:

    -(void)didBeginContact:(SKPhysicsContact *)contact`
    {
    NSLog(@"contact detected");
    
    SKPhysicsBody *firstBody;
    SKPhysicsBody *secondBody;
    
    if (contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask)
    {
        firstBody = contact.bodyA;
        secondBody = contact.bodyB;
    }
    else
    {
        firstBody = contact.bodyB;
        secondBody = contact.bodyA;
    }
    
    //Your first body is the block, secondbody is the player.
    //Implement relevant code here.
    
    }
    

    For a good explanation on implementing collision detection, look at this tutorial.

提交回复
热议问题