【问题标题】:App crashes when trying to add SKNode from if statement尝试从 if 语句添加 SKNode 时应用程序崩溃
【发布时间】:2014-05-03 18:41:53
【问题描述】:

我正在尝试使用NSTimer 在静止背景之上创建一个移动背景,它工作正常,直到我调用命令添加另一个孩子。这是我遇到的错误。

  • Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Attemped to add a SKNode which already has a parent: <SKSpriteNode> name:'(null)' texture:[<SKTexture> 'groundGrass.png' (53 x 71)] position:{159, 35} size:{808, 71}

这是我移动地面的代码:

-(void)moveGroundGrass{

groundGrass.position = CGPointMake(groundGrass.position.x -1, groundGrass.position.y);

if (groundGrass.position.x < 160){

    [self addChild:groundGrass];
}

这是其余的:

-(id)initWithSize:(CGSize)size {

if (self = [super initWithSize:size]) {
    /* Setup your scene here */

    SKSpriteNode *background = [SKSpriteNode spriteNodeWithImageNamed:@"background"];
    background.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame));

    background.xScale = 0.9;
    background.yScale = 1.1837f;


    [self addChild:background];


    groundGrass = [SKSpriteNode spriteNodeWithImageNamed:@"groundGrass"];

    groundGrass.position = CGPointMake (404, 35);

    [self addChild:groundGrass];

    moveGround = [NSTimer scheduledTimerWithTimeInterval:0.01f target:self selector:@selector(moveGroundGrass) userInfo:nil repeats:YES];


       }
return self;

}

当 groundGrass.png 移过屏幕上应该添加另一个子节点的点时,它会崩溃...

【问题讨论】:

    标签: ios objective-c sprite-kit sknode


    【解决方案1】:

    您没有在 moveGroundGrass 方法中创建新的 groundGrass。您需要像在initWithSize: 中那样创建一个新的

    在 Obj-C 中,您创建一个像这样的对象:object *name [object new]; 其中object 可以是 f.e.界面视图。

    如果您想轻松访问您正在创建的对象,您可以将它们添加到 NSMutableArray 但如果您只想添加它们然后对它们不执行任何操作(不推荐),您可以创建它然后将其添加到视图中。

    【讨论】:

    • 那么我如何创建一个新的groundGrass,我虽然这就是[self addChild:groundGrass];如果这有任何意义的话,或者我如何将子节点添加到父节点......当然我可以制作一个groundGrass2,但如果可能的话我宁愿不这样做是否有一个类似于[self addSubChild:groundGrass];?
    • 您认为您可以给我一个示例,使用我的代码添加另一个节点以在 groundGrass.x 通过 160 后生成,您的解释可能是正确的,但我无法理解/实现它。
    • 就像我说的对象 *name [object new];但在您的情况下,您会将对象重命名为 SKSpriteNode,因为那是您正在使用的对象。
    • 是的,但是当我这样做时会发生这种情况,当 groundGrass 通过坐标 160 时,每 0.01 秒添加一个子节点......而不是每 0.01 秒添加一个新节点(NSTimer moveGround) 我怎样才能让它只添加一次,一旦它通过了那个点,而不是每 0.01 秒?
    • 我想你可以自己弄清楚。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多