1

我有一个Gamehud我想显示对象名称的地方。主场景中有很多对象/精灵我想做的是在Gamehud.

问题是如果我GamehudCCsprite类中分配它会创建新实例并且不会更新 current 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];
    }
}

我的游戏界面

+(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];
}
4

2 回答 2

1

首先使用单例,否则每次调用都会创建一个新的 GameHub +(id) gamehud。我认为这可能是您的问题:您将一个 GameHUD 添加到场景中并调用另一个 GameHUD 对象的 showName:。另一个问题是你的-(id)init- 你不回来self!所以你永远不会得到你的 GameHUD

static GameHUD *sharedInstance = nil;
+(id) gamehud {
    if( !sharedInstance ) {
        sharedInstance = [[GameHUD alloc] init]
    }
    return sharedInstance;
}

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

       sharedInstance = self; 
    }
    return self; //i dont see this in your code!
}

从现在开始,您可以从您想要的每个点访问您的 hud,而无需处理标签。小心,这不是创建单例的最佳方式(问谷歌)。不要调用 ..alloc] init] 仅使用[GameHUD gamehud];

-(void) onTouch {
    [[GameHUD gamehud] showName:obj];
}

祝你好运!

于 2012-12-21T15:47:44.950 回答
0

您可能需要创建一个单例或类似半单例的东西。只需将新的 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];

}
于 2012-12-21T16:49:44.663 回答