SKAction repeatActionForever 不生成实体

SKAction repeatActionForever not spawning entity

基本上我有一个生成实体函数,理论上应该在屏幕上生成一个具有特定属性的随机气球。我设计的方法是这样的:

-(void)spawnBalloon
{
    int a = arc4random_uniform(self.frame.size.width);
    int b = self.frame.size.height - 50;
    CGPoint loc = CGPointMake(a, b);
    [self spawnBalloonAtPoint:loc];
}

而且这个方法很管用。当我在 init 函数中调用它时,它起作用了。当我在 touchesMoved() 函数中调用它时,它起作用了。但是,当我尝试使用

在 init 方法中调用它时
[self runAction:[SKAction repeatActionForever:[SKAction performSelector:@selector(spawnBalloon) onTarget:self]]];

失败了。为什么是这样?我是否必须只使用 "self" 中的 performSelector 函数,然后使用 NSTimer 让它永远重复?

此外,我尝试将 NSLog 放入代码中,以查看它是否在重复操作中被执行,确实如此。唯一的问题是气球没有被添加到屏幕上。我的感觉是,当我通过 repeatActionForever 调用 spawnBalloon 函数时,self 指的是不同的 class ?抱歉,如果这让我感到困惑,我对 Objective C 和 SpriteKit 还是个新手,我并没有真正阅读很多书,而是一头扎进并决定在需要时学习(但是我对 Java/C 有丰富的知识)

编辑: 我发现如果我没有 repeatForever 操作,代码将执行并工作。但是,如果它在那里,它就不起作用。

试试这个:

[self runAction:[SKAction repeatActionForever:[SKAction sequence:@[
                                                                   [SKAction waitForDuration:0.1],
                                                                   [SKAction performSelector:@selector(spawnBalloon) onTarget:self]
                                                                   ]]]];

作为对 DFrog 答案的补充,它会给你想要的结果,我想你会发现理解为什么你的代码在使用 repeatActionForever: 方法时不起作用。

repeatActionForever: 方法需要非瞬时动作才能工作。这是来自文档:

The action to be repeated must have a non-instantaneous duration.

瞬间动作

An instantaneous action starts and completes in a single frame of animation. For example, an action to remove a node from its parent is an instantaneous action because a node can’t be partially removed. Instead, when the action executes, the node is removed immediately.

非瞬时动作

A non-instantaneous action has a duration over which it animates its effects. When executed, the action is processed in each frame of animation until the action completes

如您所知,performSelector:onTarget 创建了一个调用某个对象方法的操作,但该操作立即 运行。引用自文档:

...When the action executes, the target object’s method is called. This action occurs instantaneously...

正如我上面提到的,repeatActionForever: 方法需要一个具有 非瞬时 持续时间的动作,所以这就是为什么它不会像您预期的那样工作。