如何在 swift spritekit 中创建重复片段

How to create repeating segments in swift spritekit

正如您在下面的代码中所看到的,我尝试在屏幕的左下角建立一个节点,然后再将它们排成一排,使它们紧挨着彼此,并且没有堆叠。但是,这段代码不起作用,也没有显示我试图放入的图像。如果有人能解释一下为什么它不起作用以及我该如何解决它,我将不胜感激。

是的,这个函数只是在代码的不同部分被调用

let obstacleSquare = SKSpriteNode(imageNamed: "obstaclesquare")
func createBottomBound() {
    obstacleSquare.position = CGPoint(x: 0 + frame.size.width/40, y: 0 + frame.size.width/40)
    obstacleSquare.size = CGSize(width: frame.size.width/20, height: frame.size.width/20)
    var i = 0
    while (i<20) {
        obstacleSquare.removeFromParent()
        addChild(obstacleSquare)
        obstacleSquare.run(SKAction.moveBy(x: obstacleSquare.size.width*CGFloat(i), y: 0, duration: 0))
        i += 1
    }
}

您好,看看下面的区别

func createBottomBound() {
    var i = 0
    while (i<20) {
        //Create a new instance here
        let obstacleSquare = SKSpriteNode(imageNamed: "obstaclesquare")

        /*I'm surprised your code ran as this line should of made it crash, you are asking it to remove the obstacle before you even added it. Any way you do not need this*/
        //obstacleSquare.removeFromParent()

        /*You don't want the objects stacked so you can change the position in the loop*/
        obstacleSquare.position = CGPoint(x: 0 + frame.size.width/(40 - i*2), y: 0 +     frame.size.width/(40 - i*2))
        obstacleSquare.size = CGSize(width: frame.size.width/20, height: frame.size.width/20)
        addChild(obstacleSquare)
        obstacleSquare.run(SKAction.moveBy(x: obstacleSquare.size.width*CGFloat(i), y: 0, duration: 0))
        i += 1
    }
}