【问题标题】:Why is Cocos2D update only firing when adding sprite to parent's CCSpriteBatchNode from child为什么 Cocos2D 更新仅在从子级向父级的 CCSpriteBatchNode 添加精灵时触发
【发布时间】:2013-06-10 23:32:03
【问题描述】:

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

我有一个 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];

 }

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

-(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

【问题讨论】:

  • 确保 mySprite 属性指向 mySprite 实例?也许由于某种原因,当你想从你的游戏层添加它时它是 nil
  • 肯定不是 nil,因为它显示在屏幕上,但计划的更新没有触发,所以它没有移动......
  • 你不能说它“绝对不是零”,因为这只是一个属性。您可以创建 sprite(您的 Food 类中的 mySprite 变量),但声明属性有点错误,因此 foodInstance.mySprite 可能为 nil。

标签: cocos2d-iphone ccspritebatchnode


【解决方案1】:

Ruben,mySprite 是一个带有retain 属性的属性吗? Food 类可能会丢失此属性的内存引用...

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

在 .m 或 .h 上,放:

@property (nonatomic, retain) CCSprite *mySprite

在初始化时,使用:

self.mySprite = [CCSprite spriteWithFile:@"bol.png"];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-25
    • 2020-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多