Created
August 31, 2022 13:50
-
-
Save christianselig/e584ac8143d6f980a98851afa8e99797 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
import SpriteKit | |
class SKAnimatedAction { | |
let movementAction: SKAction | |
let animationAction: SKAction | |
let animationKey: String | |
init(movementAction: SKAction, animationAction: SKAction, animationKey: String) { | |
self.movementAction = movementAction | |
self.animationAction = animationAction | |
self.animationKey = animationKey | |
} | |
} | |
extension SKSpriteNode { | |
func run(animatedAction: SKAnimatedAction, completion: (() -> Void)? = nil) { | |
run(animatedAction.animationAction, withKey: animatedAction.animationKey) | |
let sequence = SKAction.sequence([ | |
animatedAction.movementAction, | |
SKAction.run { [weak self] in | |
self?.removeAction(forKey: animatedAction.animationKey) | |
completion?() | |
} | |
]) | |
run(sequence) | |
} | |
} | |
class MyScene: SKScene { | |
override func didMove(to view: SKView) { | |
let node = SKSpriteNode(image: "character.png") | |
addChild(node) | |
node.run(animatedAction: walkingAction()) { | |
node.run(animatedAction: self.jumpingAction()) | |
} | |
} | |
func walkingAction() -> SKAnimatedAction { | |
let moveAction = SKAction.moveTo(x: 50.0, duration: 5.0) | |
let animationAction = SKAction.repeatForever(SKAction.animate(with: walkingTextures, timePerFrame: 0.125)) | |
return .init(movementAction: moveAction, animationAction: animationAction, animationKey: "walk") | |
} | |
func jumpingAction() -> SKAnimatedAction { | |
let moveAction = SKAction.moveTo(x: 80.0, duration: 5.0) | |
let animationAction = SKAction.repeatForever(SKAction.animate(with: jumpingTextures, timePerFrame: 0.125)) | |
return .init(movementAction: moveAction, animationAction: animationAction, animationKey: "jump") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment