How can I animate a SKSpriteNode
from a array of CGPoints
in swift? I would also like the SKSpriteNode
to rotate towards the next position it is going to. 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:
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).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.