【发布时间】:2012-01-23 09:34:13
【问题描述】:
我正在使用tutorial 制作一个简单的应用程序。与示例应用程序不同的是,我想从一开始就展示我的弹丸/物体,而不是一触即发。同样,我这样做:
-(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'
【问题讨论】:
-
CCLOG 两个 location.x 和 projectile.position.x 并发布值...同时发布更新弹丸位置的代码
-
@Shubhank:感谢您的快速回复。 location.x = 156 而 projectile.position.x 结果为 0。另外我编辑了我的问题并在触摸事件中添加了代码以及错误日志。
-
你的弹丸是在同一个文件还是.h文件中声明的?请检查,因为弹丸精灵没有获得记忆。你也没有使用 _projectiles = [[NSMutableArray alloc] init];如教程中的 init 方法
-
我知道,我已经在 .h 文件中声明并且还做了 @property(nonatomic,retain) CCSprite *projectile;因此问题发生了。这就是奇怪的地方。我已经完成了 _projectiles = [[NSMutableArray alloc] init];在 init 方法中,但我认为没有必要提及所以这里没有显示。
-
NSLog offX 在这一行之后 int offX = location.x - projectile.position.x; //弹丸在这里返回0X0
标签: iphone cocos2d-iphone ccsprite