如何实现反向倒计时然后调用方法

时间:2012-06-09 08:29:56

标签: iphone objective-c cocos2d-iphone

我正在开发一款2D游戏,在我的游戏画面中,我必须在30秒到0秒之间实现反向计时器,如果玩家没有移动他的角色,他将赢,否则他将输掉游戏将结束

这是我的init方法:

-(id)init
    {
    if(self==[super init])
    {
        self.isTouchEnabled=YES;
        self.isAccelerometerEnabled=YES;
        CGSize size=[[CCDirector sharedDirector] winSize];
        screenwidth=size.width;
        screenheight=size.height;
        west_pic=[CCSprite spriteWithFile:@"west_pic.png"];
        west_pic.anchorPoint=ccp(1, 1);
        west_pic.scaleX=1.4;
        west_pic.position=ccp(size.width, size.height);
        [self addChild:west_pic];
        label1=[CCLabelTTF labelWithString:@"Level One" fontName:@"Arial" fontSize:20];
        label1.position=ccp(size.width/3.8,size.height/1.2);
        [self addChild:label1];
        label2=[CCLabelTTF labelWithString:@"Lives :" fontName:@"ArcadeClassic" fontSize:18];
        label2.position=ccp(size.width/1.5,size.height/8.2);
        [self addChild:label2];
        player=[CCSprite spriteWithFile:@"player.png"];
        player.position=ccp(size.width/1.7, size.height/2);
        player.scale=0.2;
        player.tag=2;
        player.anchorPoint=ccp(1, 0);
        [self addChild:player];
        [self schedule:@selector(updateplayer:) interval:1.0f/60.0f];

    }
        return self;
    }

1 个答案:

答案 0 :(得分:0)

例如,您可以拥有一个具有秒数的实例,该玩家不得移动角色,那么您必须拥有ssome事件方法来了解角色何时开始和停止移动,创建可更新标签(如果您想要显示)剩下的时间到玩家)和安排计时器,这将减少秒数。喜欢这样的

- (void) onEnter
{
    [super onEnter];

    // if player character not move on start
    [self schedule:@selector(reduceRestTime) interval:1.f];
}

- (void) onExit
{
    [self unscheduleAllSelectors];
    [super onExit];
}

- (void) onCharacterStop
{
    m_restTime = // your time left. in your case, 30 sec
    // if you have time label
    [self updateRestTimeLabel];

    [self schedule:@selector(reduceRestTime) interval:1.f];
}

- (void) onCharacterBeginMovement
{
    [self unscheduleSelector:@selector(reduceRestTime)];    
}

- (void) reduceRestTime
{
    m_restTime--;

    // if you have time label
    [self updateRestTimeLabel];

    if( m_timeLeft == 0 )
    {
        [self unscheduleSelector:@selector(reduceRestTime)];

        // your win code
    }

}

- (void) updateRestTimeLabel
{
    [m_timeLabel setString:[NSString stringWithFormat:@"Time left: %d", m_timeLeft]];
}