Aero Wang
Aero Wang

Reputation: 9217

SpriteKit Detect End of Contact After Detecting Begin of Contact

This is what I try to accomplish:

Two sprite nodes in the scene, and self is an edge loop.

If nodeA touches nobeB, and stop. >> Win

If nodeA touches self. >> Lose

If nodeA touches nobeB but didn't stop and touches self. >> Lose

Therefore I need something that works like this:

typedef NS_OPTIONS(aero, SpriteNodeCategory)
{
    SpriteNodeCategoryA    = 1 << 0,
    SpriteNodeCategoryB    = 1 << 1,
};

-(void)didBeginContact:(SKPhysicsContact *)contact
{
    aero collision = (contact.bodyA.categoryBitMask | contact.bodyB.categoryBitMask);
    if (collision == (SpriteNodeCategoryA|SpriteNodeCategoryB)) {
        //something here I don't know...
    }
    if (collision == (SpriteNodeCategoryA|SpriteNodeCategoryB)) {
        NSLog(@"FAIL");
    }
}

Upvotes: 0

Views: 284

Answers (2)

James Wayne
James Wayne

Reputation: 1912

Okay so this is going to be a little difficult.

First of, you can use "didSimulatePhysics" to get the update of your simulation

-(void)didSimulatePhysics
{
    if (_yourNode.physicsBody.angularVelocity == 0 && newGame) {
        if (_yourNode.userData[@"winningCondition"]) {
            [self win];
        };
    }
}

this does is that it updates and see if you have a winning condition - which is gotten from collision (think: reverse engineering)

P.S. _yourNode.physicsBody.angularVelocity == 0 meaning your node is completely still

-(void)didBeginContact:(SKPhysicsContact *)contact
{
    uint32_t collision = (contact.bodyA.categoryBitMask | contact.bodyB.categoryBitMask);
    if (collision == (CNPhysicsCategoryNodeA|CNPhysicsCategoryNodeB)) {
        _yourNode.userData = [@{@"winningCondition":@(YES)} mutableCopy];
    }
    if (collision == (CNPhysicsCategoryNodeA|CNPhysicsCategoryEdge)) {
        [self lose];
    }
}

-(void)didEndContact:(SKPhysicsContact *)contact
{
    uint32_t collision = (contact.bodyA.categoryBitMask | contact.bodyB.categoryBitMask);
    if (collision == (CNPhysicsCategoryNodeA|CNPhysicsCategoryNodeB)) {
        _yourNode.userData = [@{@"winningCondition":@(NO)} mutableCopy];
    }
}

So basically when A touches B, it gives you a winning condition through adding a "userData" to your node.

The rest is pretty straight forward. I think you get it.

Upvotes: 1

Greg
Greg

Reputation: 25459

You have another method delegate (SKPhysicsContactDelegate) which do the job you asking about:

- (void)didEndContact:(SKPhysicsContact *)contact

Upvotes: 2

Related Questions