Swift, How to call a function that's in an extension in my GameScene?

Viewed 84

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?

1 Answers

The shake method is declared in an extension of UIView, meaning that it can be called on any UIView instance.

SKView is a kind of UIView that holds a SKScene. SKScenes have a view property that you can use to access the SKView. Therefore, you can call shake in your scene like this:

self.view?.shake()
Related