简体   繁体   English

如何在Sprite Kit中通过一组CGPoint进行动画制作-Swift

[英]How to animate through an array of CGPoints in Sprite Kit - Swift

How can I animate a SKSpriteNode from a array of CGPoints in swift? 如何SKSpriteNodeCGPoints数组中为CGPoints设置动画? I would also like the SKSpriteNode to rotate towards the next position it is going to. 我也希望SKSpriteNode可以旋转到下一个位置。 Any help would be appreciated. 任何帮助,将不胜感激。

You can do it like this: 您可以这样做:

import SpriteKit

class GameScene: SKScene,SKSceneDelegate {


    override func didMove(to view: SKView) {

        //1. create points
        let points = [CGPoint(x:120,y:20),CGPoint(x:220,y:20),CGPoint(x:40,y:320)]

        var actions = [SKAction]()

        //2. Create actions
        for point in points {
            actions.append(SKAction.move(to: point, duration: 1))
        }

        let sprite = SKSpriteNode(color: .white, size: CGSize(width: 100, height: 100))

        addChild(sprite)

        //3. Create the action sequence from previously created actions
        let sequence = SKAction.sequence(actions)

        //4. Run the sequence (use the key to stop this sequence)
        sprite.run(sequence, withKey:"aKey")

    } 
}

As per @KnightOfDragon's suggestion, you can make a path and make the node to follow it, like this: 按照@KnightOfDragon的建议,您可以创建一条路径并使节点遵循该路径,如下所示:

class GameScene: SKScene {


    override func didMove(to view: SKView) {


        //1. create points
        let points = [
            CGPoint(x:frame.minX,y:frame.minY),
            CGPoint(x:frame.maxX,y:frame.maxY),
            CGPoint(x:frame.maxX,y:frame.midY),
            CGPoint.zero
                      ]

        //2. Create a path
        let path = CGMutablePath()

        //3. Define starting point
        path.move(to: points[0])

        //4. Add additional points
        for point in points[1..<points.count]{

            print("point : \(point)")
            path.addLine(to: point)
        }

        //5. Create an action which will make the node to follow the path
        let action = SKAction.follow(path, speed: 122)

        let sprite = SKSpriteNode(color: .white, size: CGSize(width: 100, height: 100))

        addChild(sprite)

        sprite.run(action, withKey: "aKey")

    }
}

This might be more convenient than accepted answer in the case that you want the node to orient to the path that it follows ( zRotation property animates so that the node turns to follow the path). 如果希望节点定向到它遵循的路径( zRotation属性具有动画效果,以便节点转向遵循该路径),这可能比接受的答案更方便。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM