如何在场景外正确删除节点

how to properly remove nodes once outside of scene

我正在制作一个游戏,在这种情况下,“箭头”是一个节点,每隔几秒就会落在屏幕顶部到底部的随机区域中。问题是当节点到达屏幕的最后 10 个左右时,它似乎几乎卡在屏幕上并停止,没有完全离开屏幕并消失。有什么办法可以解决这个问题吗?

func startTheArrow() {

    run(SKAction.repeatForever(SKAction.sequence([SKAction.run(spawnArrow), SKAction.wait(forDuration: 5.0)])))
    
} 




func spawnArrow() {
    
    let arrow = SKSpriteNode(imageNamed: "arrow")
    
    arrow.size = CGSize(width: 50, height: 50)
    arrow.physicsBody = SKPhysicsBody(rectangleOf: arrow.size)
    arrow.physicsBody?.affectedByGravity = false
    arrow.physicsBody?.categoryBitMask = ColliderType.arrow
    
    arrow.name = "Arrow"
    
    arrow.zPosition = 1
    
    arrow.position = CGPoint(x: frame.size.width * random(min: -0.45, max: 0.45), y: frame.size.height * random(min: 0.6, max: 0.7))
    
    addChild(arrow)
    
    arrow.run(
        SKAction.moveBy(x: 0.0 , y: -size.height - arrow.size.height,
                        duration: TimeInterval(random(min: 2, max: 2))))
    
    self.enumerateChildNodes(withName: "Arrow") { (node:SKNode, nil) in
        if node.position.y < -500 || node.position.y > self.size.height + 550 {
            node.removeFromParent()
            
                 
       }
   }   
} 

所以我终于找到了解决办法。出于某种原因,Xcode 不喜欢这段代码:

arrow.run(
    SKAction.moveBy(x: 0.0 , y: -size.height - arrow.size.height, duration: TimeInterval(random(min: 2, max: 2))))
    self.enumerateChildNodes(withName: "Arrow") { (node:SKNode, nil) in
    if node.position.y < -500 || node.position.y > self.size.height + 550 {
        node.removeFromParent()
    }
}   

我用下面的代码代替了这个并且节点是固定的,虽然它们没有完全离开屏幕,但场景底部没有一些奇怪的停顿和堆积。

let moveEnemy = SKAction.moveTo(y: -800, duration: 4.0)
let deleteEnemy= SKAction.removeFromParent()
let enemySequence = SKAction.sequence([moveEnemy, deleteEnemy])
enemy.run(enemySequence)