I'm making a 2D platformer game on Swift, and I want the screen to shake when the player gets hit with a weapon. I've tried a few different solutions, like making just the background sprite shake, but it just doesn't have the same effect. I found code online that creates a shake function that I believe will shake the screen, but the only problem is I don't know how to call it in my GameScene because it's defined outside of my class. For example, this is what my code looks like:
class GameScene: SKScene, SKPhysicsContactDelegate {
// code
func didBegin(_ contact: SKPhysicsContact) {
// call shake function
}
}
extension UIView {
func shake() {
let animation = CAKeyframeAnimation(keyPath: "transform.translation.x")
animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.linear)
animation.duration = 0.6
animation.values = [-20, 20, -20, 20, -10, 10, -5, 5, 0]
self.layer.add(animation, forKey: "shake")
}
}
I want to call the shake function where it says "call shake function" in my code. How would I call it?