UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: Animating SKUniforms?

Forums > Swift

@LilaQ  

Hey guys!

I'm currently trying to animate an SKUniform, is there any way to achieve this? I tried to put the value in a @State var and call the changes in an withAnimation but that didn't do the trick, the shader just "pops" to the new value.

func zoomingOut() { withAnimation { shaderScaling = 1.0 self.shaderUniform.floatValue = shaderScaling } }

This this my code, more or less. If someone has an idea on how to animate value changes here, I'd really appreciate it!

Best regards LilaQ

2      

@LilaQ  

I wrote my own Animation class for this in the end. In case someone stumbles upon the same issue:

class AnimationHelper {

    static func easeInOutSine(_ x: Double)->Double {
        return -(cos(Double.pi * x) - 1) / 2;
    }

    static func easeInOutCubic(_ x: Double)->Double {
        return x < 0.5 ? 4 * x * x * x : 1 - pow(-2 * x + 2, 3) / 2;
    }

    enum EASING {
        case none, easeInOut, easeInOutCubic
    }

    static func animate<T:BinaryFloatingPoint>(startValue: T, targetValue: T, targetTime: Double = 1.0, easing: EASING = .none, onFractionalUpdate: @escaping (T)->()) {
        let resolution = 0.01
        var currentTime = 0.0
        _ = Timer.scheduledTimer(withTimeInterval: resolution, repeats: true) { timer in
            currentTime += resolution

            if currentTime >= targetTime {
                timer.invalidate()
            }

            //  TODO:   We could add some easing funcionality here
            var timeFraction = currentTime / targetTime
            switch easing {
            case .easeInOut:
                timeFraction = easeInOutSine(timeFraction)
            case .easeInOutCubic:
                timeFraction = easeInOutCubic(timeFraction)
            default: ()
            }

            let valueFraction = targetValue - startValue
            onFractionalUpdate(T(timeFraction) * T(valueFraction) + startValue)
        }
    }

}

Cheers

2      

Excellent!

Please mark your own answer as "Solved"

2      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.