0

我刚刚开始使用Objective C,我的设计是错误的,或者我的实现是错误的,或者两者兼而有之,我什至不知道。

我在下面提供了相关信息,但我的期望是:

创建 PlayerBullet 类,这样我就可以分配类文件中预定义的数据,例如精灵文件、速度、开火时的声音等。

我认为这比每次制作子弹时在 playerShoot 函数中设置该数据要好。但是,我收到错误提示 insertObject:atIndex:] 对象不能为零。

//PlayerBullet.h
#import "cocos2d.h"
@interface PlayerBullet: CCSprite{
     CCSprite *projectile; 
}
property (nonatomic, assign) CCSprite *projectile; 
@end 

//PlayerBullet.m 
#import "PlayerBullet.h" 
@implementation PlayerBullet
-(id)init{
     projectile = [CCSprite spriteWithFile:@"projectile.png"]; 
     return self; 
 }
 @end 

 //HelloWorldLayer.h
 ...
 @interface HellowWorldLayer: CCLayerColor{
       PlayerBullet *playerBullet; 
 }
 ...

 //HelloWorldLayer.m
 ...
-(void)playerShoot:(ccTime)dt{
    CGSize winSize = [[CCDirector sharedDirector] winSize]; 
    playerBullet = [[PlayerBullet alloc] init]; 
    playerBullet.projectile.tag = 2; 
    [_projectiles addObject:playerBullet.projectile]; 
    playerBullet.projectile.position = ccp(player.position.x,player.position.y); 
    [self addChild:playerBullet.projectile]; 

    [playerBullet.projectile runAction:
     [CCSequence actions: 
      [CCMoveTo actionWithDuration:1.5  position:ccp(player.position.x,winSize.height)], 
      [CCCallBlockN actionWithBlock:^(CCNode *node){
          [node removeFromParentAndCleanup:YES]; 
          [_projectiles removeObject:node]; 
      }], 
       nil]]; 
}
4

1 回答 1

1

在我看来,您正在尝试创建一个作为 CCSprite 子类的 PlayerBullet 对象。然而,在 [playerBullet init] 你没有初始化 self.

初始化对象的典型示例:

// SomeObject.m

@implementation SomeObject

-(id)init{
    self = [super init];
    if (self) {

    }
    return self; 
}

@end 

对于你的对象,试试这个:

    //PlayerBullet.m 
#import "PlayerBullet.h" 
@implementation PlayerBullet
-(id)init{
    self = [super init]; // initialize self
    if (self) {
        projectile = [CCSprite spriteWithFile:@"projectile.png"]; 
    }
    return self; 
}
@end 
于 2013-11-13T16:24:32.330 回答