sprite kit删除特定节点

时间:2014-02-21 03:21:46

标签: ios sprite-kit

我正在尝试创造一个角色永远向右跑的游戏(游戏是风景)。在地面上有角色,角色可以跳过。目前,我正在以类似检查点的方式创建一个新的(并且有些随机)尖峰集,一旦角色达到一定距离,就会创建下一组随机组织的尖峰并且检查点距离被推回等等。随着尖峰,我有一个单独但非常相似的类似检查点的系统,用于创建构成地面的瓷砖。 这是我的代码,'endlessX'和'endlessGroundX'是检查点值:

- (void) didSimulatePhysics {
if (player.position.x > endlessX) {
    int random = player.position.x + self.frame.size.width;
    [self createSpike:random];
    endlessX += self.frame.size.width/2.2 + arc4random_uniform(30);
}
if (player.position.x + self.frame.size.width > endlessGroundX) {
    [self createGround:endlessGroundX];
    endlessGroundX += tile1.frame.size.width;
}
    [self centerOnNode: player];
 }

createSpike和createGround方法的参数只是SKSpriteNodes的'x'值。 我目前正在使用它,因为角色本身就是移动的,尖刺和瓷砖是静止的。这就是我创建角色的方式:

-(void) createPlayer {

player = [SKSpriteNode spriteNodeWithImageNamed:@"base"];
player.position = CGPointMake(self.frame.size.width/2, self.frame.size.height/2);
player.name = @"player";
player.zPosition = 60;
player.xScale = 0.8;
player.yScale = 0.8;
player.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:player.frame.size.height/2];
player.physicsBody.mass = 1;
player.physicsBody.linearDamping = 0.0;
player.physicsBody.angularDamping = 0.0;
player.physicsBody.friction = 0.0;
player.physicsBody.restitution = 0.0;
player.physicsBody.allowsRotation = NO;
player.physicsBody.dynamic = YES;
player.physicsBody.velocity = CGVectorMake(400, 0);
player.physicsBody.categoryBitMask = playerCategory;
player.physicsBody.collisionBitMask = wallCategory;
player.physicsBody.contactTestBitMask = wallCategory | spikeCategory;
[myWorld addChild:player];
  }

有了这个,角色永远不会失去任何摩擦力或任何其他力量。然后,我使用苹果在冒险游戏中使用的“节点中心”方法,以便角色始终保持在屏幕上的相同x位置:

- (void) centerOnNode: (SKSpriteNode *) node {
CGPoint cameraPositionInScene = [node.scene convertPoint:node.position fromNode:node.parent];
node.parent.position = CGPointMake(self.frame.size.width/5 + node.parent.position.x - cameraPositionInScene.x, node.parent.position.y);
  }

我在'didSimulatePhysics'中调用此方法。

When I run this for some time, the programs gets slower and slower. I am guessing that that is due to the fact that I am never removing these nodes and they are always being added. However, to fix this problem, I tried doing something like this:

-(void)update:(CFTimeInterval)currentTime {
[self enumerateChildNodesWithName:@"*" usingBlock:^(SKNode *node, BOOL *stop) {
    if (node.position.x + 50 < player.position.x) {
        [node removeFromParent];
    }
}];  
}

(+50只是为了确保节点在移除之前不在屏幕上) 但是,当我这样做时,程序将删除所有精灵节点,而不是删除满足'if'语句的特定节点。是否有一种不同的方法或其他我想要修复的方法?或者有没有其他简单的方法来删除特定的节点?

1 个答案:

答案 0 :(得分:2)

缺少一些细节,例如你如何制作尖峰动画,让它变得有点难以过于具体。然而,根据你所分享的内容,我猜你可能正在寻找类似这样的东西:

    SKAction *moveSpikeAction = [SKAction moveToX:-50 duration:5];
    SKAction *removeSpikeAction = [SKAction removeFromParent];
    SKAction *spikeSequence = [SKAction sequence:@[moveSpikeAction, removeSpikeAction]];
    [yourSpikeSpriteNode runAction:spikeSequence];

这个想法只是当尖峰动画到屏幕外位置时,你可以使用removeFromParent动作来清除它。