0

我正在使用本教程制作一个简单的应用程序。与示例应用程序不同的是,我想从一开始就展示我的弹丸/物体,而不是一触即发。同样,我这样做:

-(id) init
{
    if((self=[super init]))
    {
        [[SimpleAudioEngine sharedEngine]setEnabled:TRUE];
        winSize = [CCDirector sharedDirector].winSize;
        projectile = [CCSprite spriteWithFile:@"abc.png"];
        projectile.position = spriteOffset;
        self addChild:projectile];
        self.isTouchEnabled = YES;
        //some other code
   }
}

然后在触摸同一个物体/弹丸时,我需要将它移动到我移动到的方向。我正在做同样的事情:

- (void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    // Choose one of the touches to work with
    UITouch *touch = [touches anyObject];
    CGPoint location = [touch locationInView:[touch view]];
    location = [[CCDirector sharedDirector] convertToGL:location];

    // Determine offset of location to projectile
    int offX = location.x - projectile.position.x; //Projectile returns 0X0 here
    int offY = location.y - projectile.position.y;

    float scalarX = 1.0f;

    if (offX < 0.0f)
        scalarX = -1.0f;

    int realX = scalarX * (winSize.width + (projectile.contentSize.width/2));//winSize.width + (food.contentSize.width/2);
    float ratio = (float) offY / (float) offX;
    int realY = (realX * ratio) + projectile.position.y;
    CGPoint realDest = ccp(realX, realY);

    int offRealX = realX - projectile.position.x;
    int offRealY = realY - projectile.position.y;
    float length = sqrtf((offRealX*offRealX)+(offRealY*offRealY));
    float velocity = 480/1; // 480pixels/1sec
    float realMoveDuration = length/velocity;

    [projectile runAction:[CCSequence actions:
                       [CCMoveTo actionWithDuration:realMoveDuration position:realDest],
                       [CCCallFuncN actionWithTarget:self selector:@selector(spriteMoveFinished:)],
                       nil]];
    [_projectiles addObject:projectile];  //ERROR SIGABRT

}

在上面的代码中,在这一行int offX = location.x - projectile.position.x;我的精灵返回到 0X0。我没有得到我犯错的地方。首先,它会在屏幕上显示对象,但在触摸事件时,它会消失。我也合成了 CCSprite,但成功了。是否有任何其他方法或我正在执行的任何错误?如果有任何想法,请提供帮助。谢谢你。

ERROR : Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSMutableArray insertObject:atIndex:]: attempt to insert nil object at 0'
4

2 回答 2

1

projectile可能会成为自动释放池的受害者并因此返回0x0. asprojectile被初始化为非保留。这不是 COCOS2D 相关的问题。这基本上是一个 Objective-C 内存管理问题。

做一件事,使弹丸为

@property(非原子,保留)

然后在

-(id) init

进行此更改:

        self.projectile = [CCSprite spriteWithFile:@"abc.png"];
        self.projectile.position = spriteOffset;
        [self addChild:self.projectile];

希望这能解决您面临的问题

于 2012-01-23T09:50:28.187 回答
0

实际上,由于弹丸精灵是作为子元素添加到 init 中的,因此自动释放它的唯一方法是在代码的其他地方将弹丸作为子元素移除。你必须找到发生这种情况的地方。仅通过保留强制它“粘”可能会破坏有关精灵删除原因的逻辑。

于 2012-01-23T10:54:26.323 回答