简体   繁体   中英

Organising animations in Swift

I have a number of different scenes in Swift. Each scene animates a number of objects briefly. These objects are disparate and all animate in their own unique ways.

The issue is that now I have lines and lines of code for each scene, all of which govern a different SKAction. Is there a way to minify this kind of code, or to restructure the code so that we put it all in one place (and draw from it somewhere else)?

One of my ideas is to make all of the animated nodes a specific class, like AnimatedNode, and then put all the animations in there; as separate functions. This would effectively remove the code from the scene.swift file. Is this the best I can do, or is there some other approach to this that I don't see?

EDIT: My animation code runs 100+ lines across every scene, but as an example of how animations are performed on one such node, this is what it looks like:

// can
        let can = bgNode.childNode(withName: "can")
        let tip = SKAction.rotate(byAngle: CGFloat(GLKMathDegreesToRadians(10)), duration: 0.5)
        let tipSound = SKAction.playSoundFileNamed("pot", waitForCompletion: false)
        can?.run(SKAction.sequence([tip, tipSound, tip.reversed()]))

SKActions were meant to be re-used or at least pre-loaded. Your idea is good, because cluttering your scenes with the same code over and over is poor design.

You can make an ActionManager, that has properties for each action you want to run already pre-loaded as a property.. this will increase performance of your game, especially if you are using it more than once.

There are multiple ways to do this, but a plain function (though not as performant as properties) is a good way to at least organize your code.

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.

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