如何让一个button持续不断地调用一个函数(SpriteKit)

我正在使用sprite套件进行游戏,当按住左/右移动button时,我希望我的angular色在屏幕上移动。 问题在于,只有在轻按button时,他才会移动,而不是保持。 我到处寻找解决scheme,但似乎没有任何工作!

这是我的代码;

class Button: SKNode { var defaultButton: SKSpriteNode // defualt state var activeButton: SKSpriteNode // active state var timer = Timer() var action: () -> Void //default constructor init(defaultButtonImage: String, activeButtonImage: String, buttonAction: @escaping () -> Void ) { //get the images for both button states defaultButton = SKSpriteNode(imageNamed: defaultButtonImage) activeButton = SKSpriteNode(imageNamed: activeButtonImage) //hide it while not in use activeButton.isHidden = true action = buttonAction super.init() isUserInteractionEnabled = true addChild(defaultButton) addChild(activeButton) } //When user touches button override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { action() //using timer to repeatedly call action, doesnt seem to work... self.timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(getter: Button.action), userInfo: nil, repeats: true) //swtich the image of our button activeButton.isHidden = false defaultButton.isHidden = true } code.......... 

在我的游戏场景中

 // *** RIGHT MOVEMENT *** let rightMovementbutton = Button(defaultButtonImage: "arrow", activeButtonImage: "arrowActive", buttonAction: { let moveAction = SKAction.moveBy(x: 15, y: 0, duration: 0.1) self.player.run(moveAction) }) 

你知道什么时候触摸button,因为touchesBegan被调用。 然后您必须设置一个标志来指示该button被按下。

 override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { let touch = touches.first! if leftButton.containsPoint(touch.locationInNode(self)) { leftButtonIsPressed = true } if rightButton.containsPoint(touch.locationInNode(self)) { rightButtonIsPressed = true } } 

update() ,调用你的函数那个标志是真的:

 update() { if leftButtonIsPressed == true { moveLeft() } if rightButtonIsPressed == true { moveRight() } } 

调用touchesEnded时, touchesEnded标志设置为false:

 override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) { let touch = touches.first! if leftButton.containsPoint(touch.locationInNode(self)) { leftButtonIsPressed = false } if rightButton.containsPoint(touch.locationInNode(self)) { rightButtonIsPressed = flase } } 

编辑:

正如KoD所指出的那样,一个更SKAction方法(用于移动button)是SKAction ,它不需要标志:

  1. moveTo x:0moveTo x:frame.width定义SKActions moveTo x:frame.width in didMoveTo(View:)
  2. touchesBegan ,在正确的对象上运行正确的SKAction,指定SKAction的一个键。
  3. touchesEnded ,移除相关的SKAction。

你需要做一些math运算来计算你的物体需要移动的点数,然后根据这个距离和移动速度(以每秒点数)为SKAction设置一个持续时间。

或者,(感谢KnightOfDragons)创build一个SKAction.MoveBy x:它移动一小段距离(根据你想要的移动速度),持续时间为SKAction.MoveBy x:秒。 当button被触摸时,永远重复这个动作( SKAction.repeatForever ),当释放button时移除重复的SKAction。