Detecting collisions in sprite kit

前端 未结 2 1860
清歌不尽
清歌不尽 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.

    0 讨论(0)
  • 2020-11-27 06:17

    Handling collisions is a bit messy. :) There are a number of approaches, but one place you should start with is this fairly simple example from Apple. The readme provides a good intro, and then you can start poking around with the code.

    Another approach (which Apple mentions in their guide) is to use Double Dispatching (see wikipedia for a long desc). I wouldn't start by trying to grok that approach right off however. It is a somewhat advanced approach given it depends on dynamic selectors and similar techniques to enable the magic to take place. However, even with that caveat, you can find a simple example someone put together on how to do it, along with a lot of supporting description here.

    0 讨论(0)
提交回复
热议问题