我有一个Gamehud,我想在其中显示对象的名称。我想要做的主要场景中有很多对象/精灵是在Gamehud上显示所选(触摸)对象的名称。

问题是,如果我在Gamehud类中分配CCsprite,它将创建新实例,并且不更新当前Gamehud。如果我使用GameHUD *gamehud= (GameHUD *)[self.parent getChildByTag:99];之类的东西,则什么也不会发生,我无法将对象发送到GameHud类。

那么在ccsprite or ccnode类中更新游戏界面的正确方法是什么?

主要场景

-(id) init
{
    if ((self = [super init]))
    {
        gameHud = [GameHUD gamehud];
        [self addChild:gameHud z:2 tag:99];
    }
}

我的GameHud
+(id) gamehud
{
    return [[self alloc] init];
}

-(id) init
{
    if ((self = [super init]))
    {
        //bunch of labels
    }
}


-(void)showName: :(Object *)obj
{
    NSLog(@"Object name is %@", obj.name);
    [_labelSpeed setString:obj.name];
}

在对象类中:CCSprite
-(void) onTouch
{
    //obj is the object with name property that I want to use
    GameHUD *gamehud=  (GameHUD *)[self.parent getChildByTag:99]; // does not send the obj to gamehud and showName is not called
    //GameHud *gamehud= [GameHud alloc] init]; // this displays nslog but doesnt update _label
    [gamehud showName:obj];
}

最佳答案

您可能需要创建一个单例或半个单例。只需将新的nsobject类名称“SingletonGameHud”添加到您的应用中

SingletonGameHud.h

#import <Foundation/Foundation.h>
#import "GameHUD.h"

//create singleton class to use gamehud in movingobject class
@interface SingletonGameHud : NSObject
{
    GameHUD *gamingHud;

}

@property(nonatomic,strong) GameHUD *gamingHud;

+(SingletonGameHud *)sharedInstance;


@end

SingletonGameHud.m
#import "SingletonGameHud.h"
#import "GameHUD.h"

@implementation SingletonGameHud

@synthesize gamingHud=_gamingHud;


+ (SingletonGameHud *)sharedInstance
{
    static SingletonGameHud *sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[SingletonGameHud alloc] init];
        // Do any other initialisation stuff here
    });
    return sharedInstance;
}

- (id)init {
    if (self = [super init]) {
        _gamingHud = [GameHUD hud];

    }
    return self;
}

@end

在您的游戏场景中
SingletonGameHud *sharedInstance= [SingletonGameHud sharedInstance];
hud = sharedInstance.gamingHud;
[self addChild:hud z:2 tag:99];

在您的触摸式方法调用中
-(void) onTouch
{
    SingletonGameHud *sharedInstance= [SingletonGameHud sharedInstance];
    [sharedInstance.gamingHud showName:obj];

}

关于objective-c - 如何在CCSprite或CCNode,Cocos2d中更新gamehud,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13979364/

10-09 07:56