override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let touch = touches.first
let positionInScene = touch!.location(in: self)
let touchedNode = self.atPoint(positionInScene)
if let name = touchedNode.name {
if name == "jumpbutton" {
let wait = SKAction.wait(forDuration: 3)
let boost = SKAction.applyImpulse(CGVector(dx: 0.0, dy: 160.0), duration: 0.1)
let action = SKAction.group([boost, wait])
player!.run(action)
print("jumpbutton")
}
Here is my code where I tried to set a cool down of 3 seconds before the jump button could be pressed again. Thanks for any help.
2
Answers
You could simply implement with actions like you were inclined to do:
To expand on this answer I would like to propose the creation of a component, so you don’t need to deal with every button press on your GameScene.
First create your button on the file SKButton.swift:
import SpriteKit
Here is an example of it working in my GameScene:
What works is creating a flag to determine whether pressing the jump button allows us to jump or it does not allow us to jump (i.e it is in cool down).
For this you create a variable called
isReady
near the top of the class and set it to true.When it comes to the touches, we want to check whether the node we are touching is the jump button (
touchedNode.name == "jump button"
), and whether the button is ready (isReady == true
). If both equate to true we can continue on. We first set the flagisReady = false
, this is so we can not immediately run this section of code again (think of someone rapidly pressing the jump button).Next part is creating the boost and running it.
Then finally, we create a wait action with a duration of 3 seconds. We run this wait action, then on completion we set the flag back to true (
isReady = true
).