我在访问我的图层时遇到了一些问题,这让我发疯了。基本上,我的层-场景层次结构如下:
M- CCLayer -保存+(CCScene)方法并加载所有其他CCLayers。
M- CCLayer -保存box2d引擎及其组件
M- CCLayer -保存背景。
Hud.m - CCLayer -持有HUD。
在编译器实现类中,我将场景和所有相关节点添加到编译器CCLayer:
@implementation Compiler
+(CCScene *) scene{
Compiler *compiler = [CompileLayer node];
CCScene *scene = [CCScene node];
[scene addChild: compiler];
//Add A Background Layer.
Background *layerBackground = [Background node];
layerBackground.position = CGPointMake(100,100);
[compiler addChild: layerBackground z: -1 tag:kBackground];
//Add The Construct.
Construct *construct = [Construct node];
[compiler addChild: construct z: 1];
//Add A Foreground Layer Z: 2
//After background is working.
//Add the HUD
HudLayer *hud = [Hud node];
[compiler addChild: hud z:3];
} 这一切都很好,我的层被添加到编译器中,编译器的场景被代理访问,正如预测的那样。
我的问题是,我试图访问我的背景CCLayers - CCsprite *背景,在构造层内,以便我可以根据我的构建游戏英雄的位置移动它。
我尝试过许多不同的方法,但我目前决定使用类方法而不是实例方法来定义CCSprite *背景,这样我就可以在我的构造层中访问它。
我还尝试过使用@properties进行访问并初始化该类的实例变量。
这是我的背景CCLayer:
@implementation Background
-(id) init
{
self = [super init];
if (self != nil)
{
CCSprite *temp = [Background bk];
[self addChild:temp z:0 tag:kBackGround];
}
return self;
}
+(CCSprite *)bk{
//load the image files
CCSprite *background = [CCSprite spriteWithFile:@"background.jpg"];
//get the current screen dimensions
//CGSize size = [[CCDirector sharedDirector] winSize];
background.anchorPoint = CGPointMake(0,0);
background.position = ccp(0,0);
return background;
}
@end这是可行的,它将图像加载到背景层。
最后,我尝试从构造层访问背景图像。
@interface Construct : CCLayer{
CCSprite *tempBack;
}
@end
@implementation Construct
-(id) init{
tempBack = [Background bk]; //The background equals an instance variable
}
-(void) tick:(ccTime)dt {
tempBack.position.x ++; // To do Something here.
tempBack.opacity = 0.5; // Some more stuff here.
}
@end这不起作用,我在某些方面收到了一个'nil‘指针,tempBack不能正确地访问后台,或者根本不能。
如何访问和修改后台CCLayers类变量+(CCSprite) bk??
发布于 2011-04-01 11:39:40
它可能不工作,因为你的tempBack iVar是在编译器层自动释放的,而你没有保留它。下面是init方法应该是什么样子:
-(id) init{
tempBack = [[Background bk] retain]; //The background equals an instance variable
}还有--别忘了在dealloc中release它。我也不确定它是否能工作,因为bk类方法会返回不同的背景精灵(尝试打印temp和tempBack变量地址,你就会看到)。
通知的更新
在背景图层中,创建精灵并将其添加到图层中。然后添加以下代码片段以订阅通知:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateBackground:) name:@"PlayerChangedPosition" object:nil];然后,在构造层的update方法(或任何其他调度方法)中,发送带有新玩家坐标的通知:
[[NSNotificationCenter defaultCenter] postNotificationName:@"PlayerChangedPosition" object:player];现在,在背景层中,实现updateBackground:(NSNotification *)aNotification方法:
- (void)updateBackground:(NSNotification *)aNotification {
// object message returns player object passed when posting notification
CGPoint newCoords = [[aNotification object] position];
// adjust background position according to player position
}https://stackoverflow.com/questions/5507840
复制相似问题