如何在多个位置动态拥有相同的精灵?我已经看到了另一个问题,但是,你只能用三个精灵来做到这一点。我想要一个动态数量的精灵。我的目标是,我正在努力制造,而不是只发射一颗子弹,我希望它能发射三颗或更多子弹。我已经完成了所有的数学运算,但是,我需要在for循环中绘制这三个精灵。这是我到目前为止所拥有的。
- (void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch * touch = [touches anyObject];
CGPoint pointOne = [touch locationInView:[touch view]];
CGSize size = [[CCDirector sharedDirector] winSize];
CGPoint position = turret.position;
CGFloat degrees = angleBetweenLinesInDegrees(position, pointOne);
turret.rotation = degrees;
pointOne.y = size.height-pointOne.y;
CCSprite *projectile = [CCSprite spriteWithFile:@"projectile.png"];
projectile.position = turret.position;
// Determine offset of location to projectile
int angle = angleBetweenLinesInDegrees(position, pointOne);
int startAngle = angle-15;
int shots = 3;
NSMutableArray *projectiles = [[NSMutableArray alloc] initWithCapacity:shots];
// Ok to add now - we've double checked position
for(int i = 0;i<shots;i++) {
[self addChild:projectile z:1];
int angleToShoot = angle;
int x = size.width;
int y = x*tan(angle);
CGPoint realDest = ccp(x,y);
projectile.tag = 2;
if (paused==0 ) {
[_projectiles addObject:projectile];
// Move projectile to actual endpoint
[projectile runAction:
[CCSequence actions:
[CCMoveTo actionWithDuration:1 position:realDest],
[CCCallBlockN actionWithBlock:^(CCNode *node) {
[_projectiles removeObject:node];
[node removeFromParentAndCleanup:YES];
}],
nil]];
}
}
}这给了我一个错误:'NSInternalInconsistencyException', reason: 'child already added. It can't be added again'
发布于 2012-12-03 04:12:58
您需要创建3个不同的精灵,并将它们全部添加为子对象。通常,要做这样的事情,最好使用CCBatchNode (看一下cocos文档)。有了batchnode,你可以在1个绘图调用中绘制所有的孩子,唯一的约束是所有的孩子都需要有相同的spriteSheet (或者在你的情况下,如果他们有相同的“文件名”)的纹理只有3个投射物,你不会有性能问题,但这是正确的设计方法,如果你将需要有几十个投射物在屏幕上,而不使用批处理节点,游戏将不会顺利运行。
重述一下:创建一个ccbatchnode,将batchnode添加为self的子节点(我假设是它的ur层或主节点)创建3个sprites,并将它们添加为batchnode的子节点
https://stackoverflow.com/questions/13673242
复制相似问题