WWDC22 SALE: Save 50% on all my Swift books and bundles! >>

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

   

@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

   

Excellent!

Please mark your own answer as "Solved"

   

Hacking with Swift is sponsored by Emerge

SPONSORED Optimize your app’s startup time, binary size, and overall performance using Emerge’s advanced app optimization and monitoring tools. Reliably measure app size, speed up your app's startup time with Emerge's Launch Booster, and much more. Emerge is actively used by many of the top mobile development teams in the world.

Find out more

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

Reply to this topic…

You need to create an account or log in to reply.

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.