Search code examples
swiftwaitskaction

Swift SKAction.waitForDuration Executing Too Fast


this is my first post. I've looked everywhere for an answer and it appears I am doing it right, but it just does't seem to be working.

I'm trying to execute a combat sequence between two nodes in Swift. After each node attacks, it is supposed to wait for its specified attack speed duration before attacking again.

Here is my code for the combat sequence:

func playerMonsterCollision(player: Character, monster: Character) {
    player.removeAllActions()
    monster.removeAllActions()

    let playerFight = player.dealDamage(monster)
    let playerWait = SKAction.waitForDuration(player.attackSpeed)
    let monsterFight = monster.dealDamage(player)
    let monsterWait = SKAction.waitForDuration(monster.attackSpeed)

    player.runAction(SKAction.repeatActionForever(SKAction.sequence([playerFight, playerWait])))
    monster.runAction(SKAction.repeatActionForever(SKAction.sequence([monsterFight, monsterWait])))
}

And this is the dealDamage function that is called:

func dealDamage(target: Character) -> SKAction {
    let action = SKAction.runBlock()
    {
        if (target.health > 0 && self.health > 0)
        {
            let damageDelt = self.calcAttack()
            target.takeDamage(damageDelt)
            print("Damage delt: \(damageDelt), \(target.name!) health: \(target.health).")
        }
        else
        {
            if self.name! == "Monster"
            {
                if !self.isAlive()
                {
                    self.removeFromParent()
                }
            }
            else
            {
                if !target.isAlive()
                {
                    target.removeFromParent()
                }
            }
        }
    }

    return action
}

The player.attackSpeed is a double, 3.0, and monster.attackSpeed is also a double, 3.5. As far as I understand, the double would represent a time in seconds, however, when I run my program it seems to be less than half a second between executions.


Solution

  • Found the problem!

    I was indeed doing everything correct, but thank you to this answer I figured out that I had changed the speed property in the creation of my objects. Once I fixed it, my code executed as expected. A few other speed related issues popped up, but they will be easy enough to fix now that I know what caused it!

    Hopefully this helps others who stumble across a similar issue with things executing too fast (or too slow). Be careful not to unintentionally change the SKSpriteNode.speed property.