SpriteKit Incorrectly Detecting Multiple Collisions

浪尽此生 提交于 2020-01-23 17:10:10

问题


I have been going through a SpriteKit tutorial that makes a Flappy Bird Style Game. One of the issues I am having, is that it is firing off the code for collision detection incorrectly.

Sometimes, this goes perfect...it hits the ground, it fires the method for when it collides with the ground. However, at seemingly random times, it will hit the ground, and fire off the method for ground collisions anywhere from 2-6 times. It doesn't matter if any other nodes are present on the screen or not. I can sit and let it drop immediately, and sometimes I get the collision code correctly ran once, other times it runs several times. Is there something wrong in this code causing it to do that?

UPDATE: It seems to be where the two objects meet on multiple intersecting points. If object A intersects with object B at 3 points, it will fire 3 times. How do you keep it from doing 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];
    }
}
- (void)pillar:(SKSpriteNode *)pillar didCollideWithBird:(SKSpriteNode *)bird
{
    NSLog(@"Did collide with bird");
    [self showGameOverLayer];
}

- (void)flappyBird:(SKSpriteNode *)bird didCollideWithBottomScoller:(SKSpriteNode *)bottomBackground
{
    NSLog(@"Did collide with scroller");

    [self showGameOverLayer];
}

回答1:


The easiest way i would solve this problem is by using this.

1st Create a BOOL called running.

BOOL running;

2nd Set running to YES when the game started

running = YES;

3rd Place an if statement around your collision code like so,

if(running == YES)
{
   //do collision detection
}
else
{
   //do nothing
}

You can also use this running bool to control various other useful parts such as your update method.



来源:https://stackoverflow.com/questions/26108429/spritekit-incorrectly-detecting-multiple-collisions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!