使精灵只跳一次

时间:2015-01-13 01:04:03

标签: ios cocos2d-iphone spritebuilder

使用Xcode,Spritebuilder和Cocos2d,我试图让玩家精灵只跳一次。因此,当玩家点击屏幕时,精灵跳跃,只有当它落地时,玩家才能再次跳跃。到目前为止,我还没有找到任何明确的解释,所以我的问题就这样了。

这是我的代码

编辑,以便代码只允许精灵跳一次:

static const CGFloat scrollSpeed = 0.4;
BOOL isInAir;
@implementation GameScene
{
    CCSprite *player1;
    CCPhysicsNode *physicsNode1;
    CCNode *ground1;
    CCNode *ground2;
}

- (void)didLoadFromCCB
{
    self.userInteractionEnabled = TRUE;
    grounds = @[ground1, ground2]    
}

- (void)update:(CCTime)delta
{
    // moves the player to the right
    player1.position = ccp(player1.position.x + delta * scrollSpeed, player1.position.y);

    // move the  camera with the player
    physicsNode1.position =  ccp(physicsNode1.position.x - (scrollSpeed *delta),     physicsNode1.position.y);

    // loop the ground
    for (CCNode *ground in grounds)
    {
        // get the world position of the ground
        CGPoint groundWorldPosition = [physicsNode1 convertToWorldSpace:ground.position];
        // get the screen position of the ground
        CGPoint groundScreenPosition = [self convertToNodeSpace:groundWorldPosition];

        // if the left corner is one complete width off the screen, move it to the right
        if (groundScreenPosition.x <= (-1 * ground.contentSize.width))
        {   
            // puts the ground piece that is about to leave the screen behind the last one
            ground.position = ccp(ground.position.x + 600, ground.position.y);
            //NSLog(@"player1 pos: %@", NSStringFromCGPoint(ground.position));
        }
    } 

    // clamp velocity
    float yVelocity = clampf(player1.physicsBody.velocity.y, -1 * MAXFLOAT, 200.f);
    player1.physicsBody.velocity = ccp(0, yVelocity);
}

- (void)touchBegan:(UITouch *)touch withEvent:(UIEvent *)event
{
    if (isInAir == NO)
    {
        [player1.physicsBody applyImpulse:ccp(0, 150)];
        isInAir = YES;
    }
}

- (BOOL) ccPhysicsCollisionBegin:(CCPhysicsCollisionPair *)pair player1:(CCNode *)player1 ground:   (CCNode *)ground
{
    NSLog(@"player is touching the ground");
    isInAir = NO;
    return YES;
}
@end

1 个答案:

答案 0 :(得分:0)

您可以使用BOOL。这是我的触摸跳转代码:

BOOL isInAir;//Make this global.
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    /* Called when a touch begins */
    UITouch *touch = [touches anyObject];
    SKSpriteNode *node = [self nodesAtPoint:[touch locationInNode:self]];

                if (isInAir == NO)
                {
                    CGFloat impulseX = 0.0f;
                    CGFloat impulseY = 600.0f;
                    [node.physicsBody applyImpulse:CGVectorMake(impulseX, impulseY) atPoint:node.position];
                    isInAir = YES;
                    //other stuff
                }
}

然后当你接触地面时,将isInAir设为NO。