Last Updated: December 28, 2016
·
3.51K
· mihailt

Swift SpriteKit - Shake Screen Effect

func shakeCamera(layer:SKSpriteNode, duration:Float) {

    let amplitudeX:Float = 10;
    let amplitudeY:Float = 6;
    let numberOfShakes = duration / 0.04;
    var actionsArray:[SKAction] = [];
    for index in 1...Int(numberOfShakes) {
        let moveX = Float(arc4random_uniform(UInt32(amplitudeX))) - amplitudeX / 2;
        let moveY = Float(arc4random_uniform(UInt32(amplitudeY))) - amplitudeY / 2;
        let shakeAction = SKAction.moveByX(CGFloat(moveX), y: CGFloat(moveY), duration: 0.02);
        shakeAction.timingMode = SKActionTimingMode.EaseOut;
        actionsArray.append(shakeAction);
        actionsArray.append(shakeAction.reversedAction());
    }

    let actionSeq = SKAction.sequence(actionsArray);
    layer.runAction(actionSeq);
}