【问题标题】:Multi-touch gesture in Sprite KitSprite Kit 中的多点触控手势
【发布时间】:2015-02-05 06:40:30
【问题描述】:

我正在使用 XCode 6 和 Sprite-Kit 在 Swift 中工作,我有许多不同的节点,但目前我只能检测到一根手指并同时移动一个节点。 我想知道如何设法检测多个手指以便同时移动多个节点。 我的实际代码是:

var location = CGFloat() // finger position
var actualNode = -1 // node touched by the finger, -1 means no node touched

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) // when a finger touch the screen
{
    for touch: AnyObject in touches
    {
        location = touch.locationInNode(self) // we detect the finger position
    } 

    for var index = 0; index < colorNode.count; index++
    {
        if nodeAtPoint(location) == colorNode[index].node
        {
            actualNode = index // the number of the node touched by the finger
        }
    }
}

override func touchesMoved(touches: NSSet, withEvent event: UIEvent) // when a finger move
{
    for touch: AnyObject in touches
    {
        location = touch.locationInNode(self) // we detect the finger position
    }

    if actualNode != -1 // if a node is touched
    {
        colorNode[actualNode].position = location // we move this node to the finger
    }
}
override func touchesEnded(touches: NSSet, withEvent event: UIEvent) // when a finger don't touch the screen anymore
{        
    actualNode = -1 // there is no node touched
}

如您所见,我只有第一根手指的position,但是如何检测多个手指位置并将每个手指分配给手指触摸的节点?

【问题讨论】:

    标签: swift sprite-kit gesture multi-touch touches


    【解决方案1】:

    同时移动多个节点相当简单。关键是独立跟踪每个触摸事件。一种方法是维护一个字典,该字典使用触摸事件作为键,将被移动的节点作为值。

    首先,声明字典

    var selectedNodes:[UITouch:SKSpriteNode] = [:]
    

    将触摸到的每个精灵添加到字典中,以触摸事件为键

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        for touch in touches {
            let location = touch.location(in:self)
            if let node = self.atPoint(location) as? SKSpriteNode {
                // Assumes sprites are named "sprite"
                if (node.name == "sprite") {
                    selectedNodes[touch] = node
                }
            }
        }
    }
    

    根据需要更新精灵的位置

    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        for touch in touches {
            let location = touch.location(in:self)
            // Update the position of the sprites
            if let node = selectedNodes[touch] {
                node.position = location
            }
        }
    }
    

    触摸结束时从字典中删除精灵

    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        for touch in touches {
            if selectedNodes[touch] != nil {
                selectedNodes[touch] = nil
            }
        }
    }
    

    【讨论】:

    • 记得设置 skView.isMultipleTouchEnabled = true 然后按照上面的说明进行操作 > 同时移动多个节点相当简单。关键是独立跟踪每个触摸事件......
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多