for循环中addChild的时间延迟导致错误!迅速

时间:2017-12-04 08:50:13

标签: arrays swift for-loop skaction addchild

这个循环我的工作正常,但我想让数组中的图像一个接一个地进入,并且它们之间有一定的特定时间。

if transitionSprite.name == nil || transitionSprite.name == "rd-d2c" || transitionSprite.name == "rd-f2c" {
        for (index, roadImage) in cityArrays[randomIndex].enumerated() {

            roadSprite = SKSpriteNode(imageNamed: roadImage)
            roadSprite.anchorPoint = CGPoint(x: 0.5, y: 0.5)
            roadSprite.position = CGPoint(x: 0, y: CGFloat(screenCounter) * roadSprite.size.height)
            roadSprite.physicsBody = SKPhysicsBody(rectangleOf: CGSize(width: self.size.width, height: self.size.height))
            roadSprite.physicsBody?.categoryBitMask = PhysicsCategory.RoadImageCategory.rawValue
            roadSprite.physicsBody?.collisionBitMask = PhysicsCategory.NoCollisionsCategory.rawValue
            roadSprite.physicsBody?.contactTestBitMask = PhysicsCategory.BroomCategory.rawValue
            roadSprite.physicsBody?.affectedByGravity = false

            roadSprite.zPosition = 1
            roadSprite.name = "Road \(index)"

            // RUNNING THE SKACTION DELAY ON THIS
            self.addChild(roadSprite)

            addCollectables()
            addJerryCans()

            if roadImage == "rdc-02_05" {
                addBackgroundDetail(detailType: "cityBridge2")
            }
            screenCounter += 1
        }

我已经创建了这个我添加到循环中的SKAction,

    loopDelay = SKAction.wait(forDuration: Double(index + 1))
    let addRoad = SKAction.run {self.addChild(self.roadSprite)}
    let action = SKAction.sequence([loopDelay, addRoad])
    self.run(action)

不确定会导致这种情况,但是当我使用SKAction延迟运行它时,我已经创建了它崩溃并给了我这个错误,

Terminating app due to uncaught exception 'NSInvalidArgumentException',
reason: 'Attemped to add a SKNode which already has a parent: 
<SKSpriteNode> name:'Road 4' texture:[<SKTexture> 'rdc-02_05' (750 x 
1334)] position:{0, 6670} scale:{1.00, 1.00} size:{750, 1334} 
anchor:{0.5, 0.5} rotation:0.00'

任何有关延迟会导致此问题的想法?感谢

1 个答案:

答案 0 :(得分:0)

您的问题是您使用属性存储roadSprite。因此,在for-in循环的每次迭代中,用新的Sprite替换存储在该属性中的内容。

当每个延迟通过时,他们都会尝试使用相同的Sprite(这是你创建的最后一个)添加孩子,因此它第一次被添加,第二次它给你上面的错误:“试图添加一个SKNode已经拥有父母“。

你想要的是将sprite创建为局部变量,并在SKAction.run闭包中捕获该变量:

select case when ceiling(43546886799090787.89) = floor(43546886799090787.89) 
       then      CONVERT(varchar, CAST(43546886799090787.89 as decimal))
       else      CONVERT(varchar, 43546886799090787.89) 
       end 
o/p --> 43546886799090787.89

select case when ceiling(43546886799090787.00) = floor(43546886799090787.00) 
   then      CONVERT(varchar, CAST(43546886799090787.00 as decimal))
   else      CONVERT(varchar, 43546886799090787.00) 
   end
o/p --> 43546886799090787

如果您仍然希望引用所有这些Sprite,那么您可能应该将它们粘贴到数组中而不是覆盖相同的属性。