1

我想创建一个简单的图层来显示一些信息,例如分数。

我设法做到了,但我不确定它是否正确:

#import "InformationLayer.h"
#import "GameScene.h"

@implementation InformationLayer

-(void) draw
{
    // Complete clear of the screen
    [self removeAllChildrenWithCleanup:true];

    // Draw my score
    [self DrawScore];
}

- (void)DrawScore
{
    // create and initialize a label
    NSString* l_sScore = [NSString stringWithFormat:@"Score : %d", [[GameScene sharedGameScene] iScore]];

    CCLabelTTF* label = [CCLabelTTF labelWithString:l_sScore fontName:@"Marker Felt" fontSize:32];

    // get the window (screen) size from CCDirector
    CGSize size = [[CCDirector sharedDirector] winSize];

    // position the label at the center of the screen
    label.position = CGPointMake(size.width - ([label texture].contentSize.width / 2), size.height*2.0/3.0);

    // add the label as a child to this Layer
    [self addChild:label];
}
@end

我一直在处理我的场景和图层,我真的不喜欢清除所有图层然后重新绘制所有内容。在我看来,这完全是矫枉过正!尽管如此,它仍然可以完成工作......

由于我处于学习曲线的底部,所以我想尽快做...我可以在这里做点更好的事情吗?

4

2 回答 2

4

这是完全错误的。只添加一次节点。draw仅当您想使用 OpenGL(或 cocos2d 的函数,如 )绘制某些东西时才使用方法ccDrawLineinit例如,您可以在 some方法中添加您的内容(标签、精灵等) 。

要更改标签的文本,请使用setString:方法。

于 2012-10-15T18:11:02.153 回答
0

所以遵循 Morion 的建议:

-(id) init
{
    if( (self=[super init] ))
    {
        [self InitLabels];

        // Scheduling the refresh method.
        [self scheduleUpdate]; 
    }
    return self;
}

// Update replaces draw !! 
-(void)update:(ccTime)delta
{
    [self UpdateLabels];
}

- (void)InitLabels
{
    // get the window (screen) size from CCDirector
    CGSize l_ScreenSize = [[CCDirector sharedDirector] winSize];
    float l_iScreenHeightPosition = l_ScreenSize.height*2.0/3.0;

    NSString* l_sScore = [NSString stringWithFormat:@"Score : %d", [[GameScene sharedGameScene] iScore]];
    NSString* l_sLevel = [NSString stringWithFormat:@"Level : %d", [[GameScene sharedGameScene] iLevel]];

    l_lblScore = [CCLabelTTF labelWithString:l_sScore
                                           fontName:@"Marker Felt" fontSize:32];

    l_lblScore.position = CGPointMake(l_ScreenSize.width - ([l_lblScore texture].contentSize.width / 2), l_iScreenHeightPosition);

    // add the label as a child to this Layer
    [self addChild:l_lblScore];

    l_lblLevel = [CCLabelTTF labelWithString:l_sLevel
                                                fontName:@"Marker Felt" fontSize:32];

    l_lblLevel.position = CGPointMake(l_ScreenSize.width - ([l_lblLevel texture].contentSize.width / 2), l_iScreenHeightPosition - ([l_lblScore texture].contentSize.height));

    // add the label as a child to this Layer
    [self addChild:l_lblLevel];
}

- (void)UpdateLabels
{
    NSString* l_sScore = [NSString stringWithFormat:@"Score : %d", [[GameScene sharedGameScene] iScore]];
    NSString* l_sLevel = [NSString stringWithFormat:@"Level : %d", [[GameScene sharedGameScene] iLevel]];

    [l_lblScore setString:l_sScore];
    [l_lblLevel setString:l_sLevel];
}

现在对我来说似乎更好:)

于 2012-10-15T18:22:54.213 回答