niX
niX

Reputation: 167

Repeating a function in swift

I've made this shake function to try add a shake effect to my menu title in my game. Thought I feel like this is a really long way of doing it! Is there any shorter/neater way of doing a repeat action like this?

Also is it possible to make this repeat forever?

func shakeMenu(){

    DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(2), execute:
        {

    let moveNodeRight = SKAction.moveBy(x: 7.0, y: 0.0, duration: 0.05)
    let moveNodeLeft = SKAction.moveBy(x: -7.0, y: 0.0, duration: 0.05)
    let moveNodeRight1 = SKAction.moveBy(x: 7.0, y: 0.0, duration: 0.05)
    let moveNodeLeft1 = SKAction.moveBy(x: -7.0, y: 0.0, duration: 0.05)
    let moveNodeRight2 = SKAction.moveBy(x: 7.0, y: 0.0, duration: 0.05)
    let moveNodeLeft2 = SKAction.moveBy(x: -7.0, y: 0.0, duration: 0.05)
    let moveNodeRight3 = SKAction.moveBy(x: 7.0, y: 0.0, duration: 0.05)
    let moveNodeLeft3 = SKAction.moveBy(x: -7.0, y: 0.0, duration: 0.05)
    let moveNodeRight4 = SKAction.moveBy(x: 7.0, y: 0.0, duration: 0.05)


    self.shake = SKAction.sequence([moveNodeRight, moveNodeLeft, moveNodeRight1, moveNodeLeft1, moveNodeRight2, moveNodeLeft2, moveNodeLeft3, moveNodeRight3, moveNodeRight4])
    self.menu.run(self.shake)

    })
}





func shakeMenu(){

    let moveRight: SKAction = .moveBy(x: 7.0, y: 0.0, duration: 0.05)
    let sequence: SKAction = .sequence([moveRight, moveRight.reversed()]
    self.menu.run(.repeat(sequence), count: 4)

}

Upvotes: 1

Views: 663

Answers (2)

Luca Angeletti
Luca Angeletti

Reputation: 59506

Don't use Grand Central Dispatch with SpriteKit

Here's the code

func shakeMenu() {
    let moveRight = SKAction.moveBy(x: 7.0, y: 0.0, duration: 0.05)
    let moveRightLeft = SKAction.sequence([moveRight, moveRight.reversed()])
    let repeatMoveRightLeft = SKAction.repeat(moveRightLeft, count: 4)
    let waitAndMove = SKAction.sequence([.wait(forDuration: 2), repeatMoveRightLeft])
    self.menu.run(waitAndMove)
}

Upvotes: 2

pbodsk
pbodsk

Reputation: 6876

How about SKAction.repeatForever (https://developer.apple.com/reference/spritekit/skaction/1417676-repeatforever)

That way you could write:

let moveNodeRight = SKAction.moveBy(x: 7.0, y: 0.0, duration: 0.05)
let moveNodeLeft = SKAction.moveBy(x: -7.0, y: 0.0, duration: 0.05)
let moveSequence = SKAction.sequence([moveNodeRight, moveNodeLeft])
let moveForever = SKAction.repeatForever(moveSequence)

self.menu.run(moveForever)

Hope that helps you.

Upvotes: 3

Related Questions