检测两个节点上的屏幕位置

时间:2014-02-17 13:34:32

标签: ios objective-c sprite-kit flappy-bird-clone

我目前正在制作 Flappy Bird -copy。放松,它只适合我和学习部分,我不会发布它,所以不要讨厌。

这只鸟被锁定在:

self.size.width/3

管道生成如下:

- (void)generatePipes {
    for (NSInteger i = 0; i < 3; i++) {
        pipeNode = [SKNode node];

        [pipeNode setName:@"pipe"];
        [pipeNode setPosition:CGPointMake(self.size.width + 100.0 + (200.0 * i), 0.0)];

        [self addChild:pipeNode];

       **BLABLABLA. Some code**

        [pipeTop setPosition:CGPointMake(0.0, arc4random_uniform(250) + 460.0)];
        [pipeBottom setPosition:CGPointMake(0.0, pipeTop.position.y - (550.0 + arc4random_uniform(10)))];

        [pipeTop setPhysicsBody:[SKPhysicsBody bodyWithRectangleOfSize:pipeTop.size]];
        [pipeBottom setPhysicsBody:[SKPhysicsBody bodyWithRectangleOfSize:pipeBottom.size]];

        [pipeTop.physicsBody setDynamic:NO];
        [pipeBottom.physicsBody setDynamic:NO];

        pipeTop.physicsBody.categoryBitMask = blockBitMask;
        pipeBottom.physicsBody.categoryBitMask = blockBitMask;
        pipeNode.physicsBody.categoryBitMask = blockBitMask;

        [pipeNode addChild:pipeTop];
        //[pipeTop attachDebugRectWithSize:pipeTop.size];
        //[pipeBottom attachDebugRectWithSize:pipeBottom.size];
        [pipeNode addChild:pipeBottom];
    }
}

这是我唯一有用的东西,是的,我是游戏开发的新手。 FirstDistance是第一个管道到达之前的距离:

        firstDistance += -moveAmount.x;

    if(touchBegan > 0 && firstDistance > (self.size.width -(self.size.width/3)- 60)){
        distanceSinceLastPipe += -moveAmount.x;


        if (distanceSinceLastPipe >= 140.0) {
            distanceSinceLastPipe = 0.0;

            score += 1;

            [_scoreLabel setText:[NSNumberFormatter localizedStringFromNumber:@(score)
                                                                  numberStyle:NSNumberFormatterDecimalStyle]];
            [self runAction:[SKAction playSoundFileNamed:@"pipe.mp3" waitForCompletion:NO]];
        }
    }

我如何告诉更新方法管道传递最有效的鸟?计算管道之间的像素并重置它?或者是否有任何方法可以检测它们何时通过?

1 个答案:

答案 0 :(得分:1)

如果您知道鸟的水平位置,您可以使用一些“简单”的数学计算管道到达该位置的时间,这意味着它已经通过了鸟。一些伪代码:

CGFloat totalDistanceForPipeToMove = pipe.position.x - endPosition.x; // endPosition == the final destination for the pipe.
CGFloat relativeSpeed = totalDistanceForPipeToMove / duration; // duration being the SKAction's duration
CGFloat distanceToBird = pipe.position.x - birdPosition.x; 
CGFloat timeThePipeReachesTheBird = distanceToBird / relativeSpeed;

然后你可以创建一个SKActionSequence,在管道开始移动的同时触发它:

SKAction *wait = [SKAction waitForDuration: timeThePipeReachesTheBird];
SKAction *addToScore = [SKAction performSelector:@selector(addToScore) onTarget:self]; // performing the addToScore method
SKAction *sequence = [SKAction sequence:@[wait, addToScore]];

实现你正在寻找的东西的另一种方法是让一个无敌的精灵跟踪birdSprite。每当这个“scoreSprite”与管道发生碰撞时,你就知道管道已经通过了那只鸟......