当同时按下两个按钮时,如何使动作发生?

How can I make an action to occur when two buttons are pressed at the same time?

我希望我的角色在我同时按下两个按钮时跳跃。我已经试过了:

if rightButton.contains(location) && leftButton.contains(location) {
    character.physicsBody?.applyImpulse(CGVector(dx: 0, dy: 50))
}

一种方法是:

  • 在检测与按钮交互的函数中,使用布尔值进行准备。
  • 然后在您的更新函数中,使用计时器添加一个时间范围,我们可以在其中同时按下两个按钮(例如 100 毫秒)。

我将在此处为您提供一些伪代码,希望对您有所帮助。

    func RightBtnClick()->Void{
        rightBtnPressed = true
    }
    func LeftBtnClick()->Void{
        leftBtnPressed = true
    }

    func Start()->Void{
        rightBtnTimer = 0
        leftBtnTimer = 0
    }

    func Update(deltatime ms:float)->Void{
        if(rightBtnPressed){
            rightBtnTimer += ms;
            if(rightBtnTimer>100){
                rightBtnTimer = 0
                rightBtnPressed=false
            }
        }

        if(leftBtnPressed){
            leftBtnTimer += ms;
            if(leftBtnTimer>100){
                leftBtnTimer = 0
                leftBtnPressed=false
            }
        }

    // Lastly let's check if both are pressed.
        if(leftBtnPressed && rightBtnPressed){
            DoStuff()
        }
    }

首先,确保在 GameViewController.swift 中启用了多点触控。

class GameViewController: UIViewController
{
    override func viewDidLoad()
    {
        super.viewDidLoad()

        // ...

        if let view = self.view as! SKView?
        {
            // ...

            view.isMultipleTouchEnabled = true
        }
    }
}

GameScene 中为您的按钮命名。在点击时,我们将创建一个列表,其中包含您手指触摸的每个具有名称的节点。如果列表中同时包含左右键,则表示他同时按下了这两个按钮。

class GameScene: SKScene
{
    override func didMove(to view: SKView)
    {
        // add name to each button

        left_button.name  = "left_button"
        right_button.name = "right_button"
    }

    func buttons_touched(_ touches: Set<UITouch>) -> [String]
    {
        // get the list of buttons we touched on each tap

        var button_list : [String] = []

        for touch in touches
        {
            let positionInScene = touch.location(in: self)
            let touchedNode = self.nodes(at: positionInScene)

            let buttons = touchedNode.compactMap { (node) -> String in
                node.name ?? ""
            }.filter({[=11=] != ""})

            button_list += buttons
        }

        return button_list
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) 
    {
        let buttons_tapped = buttons_touched(touches)

        if buttons_tapped.contains("right_button") && buttons_tapped.contains("left_button")
        {
            // jump code
        }
    }
}

您可以通过按住 Option 按钮在 Simulator 中模拟多点触控。