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