加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

swift – 在给定点的特定距离内找到所有SKNode的有效方法?

发布时间:2020-12-14 05:21:20 所属栏目:百科 来源:网络整理
导读:如果我想知道哪个或哪些节点覆盖了场景的某个点,我可以做scene.nodeAtPoint(point)或scene.nodesAtPoint(point).有没有一种有效的方法可以用圆圈做类似的事情?这是为了能够找到位置与给定点相距一定距离的所有节点. 我需要这个能够更好地处理用户点击.场景
如果我想知道哪个或哪些节点覆盖了场景的某个点,我可以做scene.nodeAtPoint(point)或scene.nodesAtPoint(point).有没有一种有效的方法可以用圆圈做类似的事情?这是为了能够找到位置与给定点相距一定距离的所有节点.

我需要这个能够更好地处理用户点击.场景相当稀少(没有太多用户活跃的精灵),所以没有必要要求用户非常精确地点击.我想在水龙头的坐标周围使用某种公差,并检测距离足够接近位置的节点.

到目前为止,我最好的想法是多次执行nodeAtPoint():在tap的位置,然后在它的各种偏移处(例如up,up-right,rigth,…,left-left).

为了确定场景中的一个或多个节点是否在触摸事件的固定距离内,1)计算触摸与每个节点之间的距离,以及2)比较该距离是否小于或等于常数.这是一个如何做到这一点的例子:
override func touchesBegan(touches: Set<UITouch>,withEvent event: UIEvent?) {
    if let touch = touches.first {
        let location = touch.locationInNode(self)
        let nodes = nodesNearPoint(self,point:location,maxDistance: 30)
        if nodes.count > 0 {
            print("node is near touch point")
        }
    }
}

// Returns an array of all SKNode objects in the subtree that near the specified point.
// If no nodes are near the point,an empty array is returned.
func nodesNearPoint(container:SKNode,point:CGPoint,maxDistance:CGFloat) -> [SKNode] {
    var array = [SKNode]()
    for node in container.children {
        // Only test sprite nodes (optional)
        if node is SKSpriteNode {
            let dx = point.x - node.position.x
            let dy = point.y - node.position.y

            let distance = sqrt(dx*dx + dy*dy)
            if (distance <= maxDistance) {
                array.append(node)
            }
        }
    }
    return array
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读