Diego Benítez Diego Benítez - 5 months ago 19
Swift Question

How to animate the whole screen when colision?

I want to make the screen shake when an enemy colide with the player. I have been searching for a posible answer but I don find anything. If someone can help me, thanks.

func colisionPrincipal(enemigo: SKSpriteNode) {

if hits < 2 && circuloPrincipal.color != enemigo.color{

func shakeFrame(scene: SKScene) {

let animation: CABasicAnimation = CABasicAnimation(keyPath: "position")
animation.duration = 0.05
animation.repeatCount = 4
animation.autoreverses = true
animation.fromValue = NSValue(CGPoint: CGPointMake(scene.view!.center.x - 4.0, scene.view!.center.y))
animation.toValue = NSValue(CGPoint: CGPointMake(scene.view!.center.x + 4.0, scene.view!.center.y))
scene.view!.layer.addAnimation(animation, forKey: "position")
}

Answer

try this

func shakeFrame(scene: SKScene) {

    let animation: CABasicAnimation = CABasicAnimation(keyPath: "position")
    animation.duration = 0.05
    animation.repeatCount = 4
    animation.autoreverses = true
    animation.fromValue = NSValue(CGPoint: CGPointMake(scene.view!.center.x - 4.0, scene.view!.center.y))
    animation.toValue = NSValue(CGPoint: CGPointMake(scene.view!.center.x + 4.0, scene.view!.center.y))
    scene.view!.layer.addAnimation(animation, forKey: "position")
}

in your case try this

func shakeFrame(scene: SKScene) {

    let animation: CABasicAnimation = CABasicAnimation(keyPath: "position")
    animation.duration = 0.05
    animation.repeatCount = 4
    animation.autoreverses = true
    animation.fromValue = NSValue(CGPoint: CGPointMake(scene.view!.center.x - 4.0, scene.view!.center.y))
    animation.toValue = NSValue(CGPoint: CGPointMake(scene.view!.center.x + 4.0, scene.view!.center.y))
    scene.view!.layer.addAnimation(animation, forKey: "position")
}

if hits < 2 && circuloPrincipal.color != enemigo.color {
    shakeFrame()
}