2

我不明白为什么会发生以下情况,我希望这里的人能解释一下。

我有一个 GameLayer (CCLayer) 类和一个 Food (CCNode) 类。

在 Gamelayer 类中,我创建了一堆具有 sprite 作为属性的食物对象。我想将这些精灵添加到 CCSpriteBatchNode。

spriteBatch = [CCSpriteBatchNode batchNodeWithFile:@"bol.png"];
[self addChild:spriteBatch]; 
for (int i = 0; i < 1000; i++) {

   Food * tempfood = [Food foodWithParentNode:self];

   [spriteBatch addChild:[tempfood mySprite]];

   [self addChild:tempfood];

 }

当我使用上面的代码时,精灵都显示在屏幕上,但不会移动。(他们应该是因为我在食品类中安排了更新(见下文),并且在此更新中食品对象的位置发生了变化)

-(id)initWithParentNode:(CCNode *)parentNode{

if((self = [super init]))
{
    mySprite = [CCSprite spriteWithFile:@"bol.png"];

    CGSize screenSize = [[CCDirector sharedDirector] winSize];

    [[self mySprite] setPosition:CGPointMake(screenSize.width/2, screenSize.height/2)];

    [self scheduleUpdate];

}

return self;
}
-(void) update:(ccTime)delta
{
  ... DO SOME position calculations ...

 [[self mySprite] setPosition:CGPointMake(newX, newY)];
}

但是,如果我将添加精灵到批次的代码从游戏类移动到食物类,那么改变位置的更新确实有效并且食物在屏幕上移动。但为什么?

所以这给出了:

-(id)initWithParentNode:(CCNode *)parentNode{

if((self = [super init]))
{
    mySprite = [CCSprite spriteWithFile:@"bol.png"];

    CGSize screenSize = [[CCDirector sharedDirector] winSize];

    [[self mySprite] setPosition:CGPointMake(screenSize.width/2, screenSize.height/2)];

    [[ (GameLayer*) parentNode spriteBatch] addChild:mySprite];

    [self scheduleUpdate];

}

return self;
}

我真的看不出打电话之间的区别

[[ (GameLayer*) parentNode spriteBatch] addChild:mySprite];

来自食品类或:

[spriteBatch addChild:[tempfood mySprite]];

来自“父”GameLayer

4

1 回答 1

1

鲁本,mySprite 是具有保留属性的属性吗?Food 类可能会丢失此属性的内存引用...

在初始化时,尝试使用 self.mySprite 设置 mySprite,以保留它。

在 .m 或 .h 上,输入:

@property (nonatomic, retain) CCSprite *mySprite

在初始化时,使用:

self.mySprite = [CCSprite spriteWithFile:@"bol.png"];
于 2013-06-10T15:32:03.233 回答