2

我创建了一个类似下面的线程:

[NSThread detachNewThreadSelector:@selector(connectionFinishedThread) toTarget:self withObject:nil];

在这个方法中,我创建了一个精灵并为这个精灵提供了动画。动画不可见。

我在 Thread 方法中的代码:

CCSprite *aniSprite = [CCSprite spriteWithSpriteFrameName:@"r_anim01.png"];
aniSprite.position = ccp(50, 50);
[self addChild:aniSprite z:22];

[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:@"r_anim1.plist"];

CCSpriteBatchNode *animSheet = [CCSpriteBatchNode batchNodeWithFile:@"r_anim1.png"];
[self addChild:animSheet];

NSMutableArray *animFrames = [NSMutableArray array];
for (int i=1; i<=6; i++) {
    [animFrames addObject:
     [[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:
      [NSString stringWithFormat:@"r_anim1%d.png",i]]];
}

CCAnimation *anim = [CCAnimation animationWithSpriteFrames:animFrames delay:0.1f];
CCAction *spriteAction = [CCRepeatForever actionWithAction: [CCAnimate actionWithAnimation:anim]];

[sprite runAction:spriteAction];

为什么它会这样?

4

2 回答 2

0

CCNode 类属性的大部分更改必须在主线程上完成。Cocos2D 不像 Sprite Kit 那样支持多线程。

例如,从后台线程更改精灵的纹理肯定会崩溃。但即使是微妙的问题也可能发生,因为所有属性都已声明nonatomic

在 cocos2d 中使用线程的唯一方法是确保在后台线程中运行的任何逻辑都不会直接更改节点的属性。即在后台进行一些 AI 计算是可以的,只要 AI 参与者不是节点而是自定义类。

于 2013-12-12T17:30:07.847 回答
0

您不应该尝试从另一个线程操作 cocos2d 对象(例如 CCNode 派生对象)。持有对象的容器(CCLayer、CCScene 等)可能同时在操作它,并且没有任何典型的并发机制(互斥体)有效。

如果您需要您的精灵在每次帧更新时采取某种更新操作,则应安排容器更新并更新精灵。在 CCScene 更新期间移动精灵、更新它们的方向等是很常见的。

于 2013-12-14T00:11:51.213 回答