Sprite 工具包 - objective c:当我创建大量节点时 fps 变慢

sprite kit - objective c: slow fps when I create a lot nodes

我想创建一个 space 背景,所以我创建了一个 for 循环来创建星星。这是代码:

for (int i = 0; i<100; i++) {
SKShapeNode *star= [SKShapeNode shapeNodeWithPath:Path.CGPath];
    star.fillColor = [UIColor whiteColor];
    star.physicsBody = nil;
    int xposition = arc4random()%960;
    int yposition = arc4random()%640;
    star.position = CGPointMake(xposition, yposition);
    float size = (arc4random()%3 + 1)/10.0;
    star.xScale = size;
    star.yScale = size;
    star.alpha = (arc4random()%10 + 1 )/ 10.0;
    star.zPosition = -2;
     [self addChild:star];
}

但这需要我的很多 cpu。当代码被激活时,cpu 位于顶部 78%。(我在 iPhone 模拟器中检查代码);

有人知道怎么解决吗?谢谢。

即使离开屏幕,您的物理体也会继续计算。一旦它们离开框架,您就需要将它们移除,否则一切都会变慢。 (为了回应其他人所说的,您最终将需要一个真实的设备)。

来自此文档:Jumping Into Sprite Kit

您可以实现 "Did Simulate Physics" 方法来去除从屏幕底部掉落的星星,如下所示:

-(void)didSimulatePhysics
{
[self enumerateChildNodesWithName:@"star" usingBlock:^(SKNode *node, BOOL *stop) {
    if (node.position.y < 0)
        [node removeFromParent];
}];
}

请注意,您首先需要使用名称 属性 来设置星形的名称,如下所示:

star.name = "star"