Collision Detection with Transparent image

advertisements

I am trying to learn SpriteKit by going through a tutorial on making a Flappy Bird like Game. In my version of the game, the pipes are not pipes, and are irregularly shaped objects that don't fill up the entirety of the rectangular canvas they are drawn upon. However, since the canvas is rectangular, SpriteKit is detecting collisions when another object touches the corner, which is technically not visible. How can I correct this?

- (void)didBeginContact:(SKPhysicsContact *)contact
{
    SKPhysicsBody *firstBody, *secondBody;

    if (contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask)
    {
        firstBody = contact.bodyA;
        secondBody = contact.bodyB;
    }
    else
    {
        firstBody = contact.bodyB;
        secondBody = contact.bodyA;
    }

    if ((firstBody.categoryBitMask & pillerCategory) != 0 &&
        (secondBody.categoryBitMask & flappyBirdCategory) != 0)
    {
        [self pillar:(SKSpriteNode *) firstBody.node didCollideWithBird:(SKSpriteNode *) secondBody.node];
    }
    else if ((firstBody.categoryBitMask & flappyBirdCategory) != 0 &&
            (secondBody.categoryBitMask & bottomBackgroundCategory) != 0)
    {
        [self flappyBird:(SKSpriteNode *)firstBody.node didCollideWithBottomScoller:(SKSpriteNode *)secondBody.node];
    }
}

I only what a collision to be detected when it actually comes to contact with the picture. Instead of a pipe that fills up all the rectangular canvas I have:


In iOS 8, you can create a physics body based on the alpha channel of a texture. (See bodyWithTexture.) This gets you an exact shape, but at a high performance cost.

To balance collision accuracy with performance, or if you're also supporting iOS 7, you can instead create a physics body from a path or by combining multiple smaller physics bodies in a way that approximates the shape you need.