如何在Swift Spritekit中创建重复片段

问题描述 投票:0回答:1

您可以在下面的代码中看到,我试图在屏幕的左下角建立一个节点,然后连续增加二十个节点,使它们彼此直接相邻而不堆叠。但是,此代码无法正常工作,并且无法显示我要放入的图像。如果有人可以,请向我解释为什么它不起作用以及如何解决它,我将不胜感激。

是的,仅在代码的另一部分中调用了此函数

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
    }
}
ios swift sprite-kit nodes skaction
1个回答
0
投票

您好,看下面的区别

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), y: 0 +     frame.size.width/(40-i))
        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
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.