-->

Modify a repeating task sequence while running

2020-08-01 06:02发布

问题:

I am trying to make a repeating task where I can change the delay in which it repeats. Here is the current code I am using:

 var actionwait = SKAction.waitForDuration(self.wait)
        var actionrun = SKAction.runBlock({
            self.count+=1
            if (self.count % 2 == 0 && self.wait > 0.2){

                self.wait -= 0.1
                 actionwait.duration = self.wait
            }
            for node in self.children{
                if (node.isMemberOfClass(Dot)){
                    node.removeFromParent()
                }
            }
            var radius = CGFloat(arc4random_uniform(100) + 30)
            var newNode = Dot(circleOfRadius: radius)
            var color = self.getRandomColor()
            newNode.fillColor = color
            newNode.strokeColor = color
            newNode.yScale = 1.0
            newNode.xScale = 2.0
            newNode.userInteractionEnabled = true
            newNode.setScene(self)
            newNode.position = newNode.randomPos(self.view!)
            self.addChild(newNode)

            })

        self.runAction(SKAction.repeatActionForever(SKAction.sequence([actionwait,actionrun])))

However, it appears that because the sequence is already repeating, changing the duration of the delay does not effect anything.

回答1:

when you create actionwait it's going to save the values inside that closure and keep using them in your repeatActionForever

When you're tracking changes it's best to do that sort of thing in the update method. Using actions in this case might not be the best approach.

I'm not sure about when you (for your game) need to be checking for changes. For most things using the update method is adequate

heres one way i implement a timer in update

// MY TIMER PROPERTIES IN MY CLASS
var missleTimer:NSTimeInterval = NSTimeInterval(2)
var missleInterval:NSTimeInterval = NSTimeInterval(2)


// IN MY UPDATE METHOD
self.missleTimer -= self.delta

if self.missleTimer <= 0 {  // TIMER HIT ZERO, DO SOMETHING!
    self.launchMissle()  // LAUNCH MY MISSLE
    self.missleTimer = self.missleInterval  // OKAY LETS RESET THE TIMER
}

delta is the difference of time between this frame and the last frame. It's used create fluid motion, and track time. Things like that. This is pretty standard among spritekit projects. you usually need to use delta projectwide

declare these two properties:

// time values
var delta:NSTimeInterval = NSTimeInterval(0)
var last_update_time:NSTimeInterval = NSTimeInterval(0)

This should be how the top of your update method looks

func update(currentTime: NSTimeInterval) {
    if self.last_update_time == 0.0 
        self.delta = 0
    } else {
        self.delta = currentTime - self.last_update_time
    }

    self.last_update_time = currentTime