首页 > 解决方案 > TouchesEnded 被称为另一个按钮被点击并取消其他动作

问题描述

当玩家按住一个按钮移动然后按下射击按钮时,TouchesEnded 被调用,然后取消玩家的移动。这两个动作是分开工作的,但当它们同时被调用时就不行了。

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    super.touchesBegan(touches, with: event)

    if let touch = touches.first {
        let location = touch.location(in: self)

        let objects = nodes(at: location)
        for node in objects {
            if node.name == "leftBtn" {
                player.run(player.leftMovement, withKey: "leftMovement")
            } else if node.name == "rightBtn" {
                player.run(player.rightMovement, withKey: "rightMovement")
            } else if node.name == "upBtn" {
                let jump = SKAction.applyImpulse(CGVector(dx: 0, dy: 1000), duration: 0.2)
                player.run(jump, withKey: "jump")
            } else if node.name == "downBtn" {
                let downMovement = SKAction.applyImpulse(CGVector(dx: 0, dy: -500), duration: 0.2)
                player.run(downMovement, withKey: "downMovement")
            } else if node.name == "shootBtn" {
                player.shoot()
            }
        }
    }
}

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {

    player.removeAction(forKey: "leftMovement")
    player.removeAction(forKey: "rightMovement")
    player.removeAction(forKey: "jump")
    player.removeAction(forKey: "downMovement")
}

我希望这两个动作独立于另一个动作,但不幸的是,事实并非如此。

标签: iosswiftsprite-kittouchsprite

解决方案


这可能是因为当您触摸拍摄按钮时,touchesEnded也会被调用,这将取消您的所有动作。

与您在方法中检查哪些节点被触摸的touchesBegan方式类似,您需要检查是否按下了拍摄按钮touchesEnded

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touch = touches.first {
        let location = touch.location(in: self)

        let objects = nodes(at: location)
        for node in objects {
            if ["leftBtn", "rightBtn", "upBtn", "downBtn"].contains(node.name) {
                player.removeAction(forKey: "leftMovement")
                player.removeAction(forKey: "rightMovement")
                player.removeAction(forKey: "jump")
                player.removeAction(forKey: "downMovement")
            }
        }
    }

推荐阅读