【问题标题】:SKTileMapNode: detecting touched Tile?SKTileMapNode:检测触摸的瓷砖?
【发布时间】:2016-10-02 10:41:02
【问题描述】:

想象一个游戏世界,它只不过是一个屏幕上有 10x10 块的 SKTileMapNode。

用户触摸了一个图块。

SKTileMapNode 是否提供了一种方法来知道哪个图块已被触摸?或者是否需要进行坐标搜索以确定哪个图块位于触摸位置?

或者还有其他方法可以做到这一点?

【问题讨论】:

    标签: ios sprite-kit touch sktilemapnode


    【解决方案1】:

    使用UITapGestureRecognizer,您可以使用SKTileMapNode 中的tileDefinition 函数检索触摸的图块。

    func handleTapFrom(recognizer: UITapGestureRecognizer) {
        if recognizer.state != .ended {
            return
        }
    
        let recognizorLocation = recognizer.location(in: recognizer.view!)
        let location = self.convertPoint(fromView: recognizorLocation)
    
        guard let map = childNode(withName: "background") as? SKTileMapNode else {
            fatalError("Background node not loaded")
        }
    
        let column = map.tileColumnIndex(fromPosition: location)
        let row = map.tileRowIndex(fromPosition: location)
        let tile = map.tileDefinition(atColumn: column, row: row)
    }
    

    那么如果你在 TilemapEditor 中添加了 userData,就可以检索到这个。包含在 userData 中的值可能是通过磁贴等的成本。

    let data = tile.userData?.value(forKey: "myKey")
    

    使用识别器的优势在于,点击、平移和长按可以在不相互干扰的单独功能中干净利落地处理。您在SKScene 中初始化手势识别器。

    override func didMove(to view: SKView) {
        let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.handleTapFrom(recognizer:)))
        tapGestureRecognizer.numberOfTapsRequired = 1
        view.addGestureRecognizer(tapGestureRecognizer)
    }
    

    【讨论】:

    • 我诚挚的歉意。我的愚蠢是巨大的。这段代码应该去哪里?
    • 你的意思是让 Pan 保持可用,这样用户就可以在比屏幕更大的 tilemap 周围平移,而无需处理 touchesBegun、touchesMoved 等?
    • 我对手势识别器一无所知。在这里阅读,似乎它们可以附加/写入任何视图。 developer.apple.com/library/content/documentation/EventHandling/… .... SKView 是 SpriteKit 唯一的 UIView 子类,这是为了被系统调用而必须去的地方吗?
    • @Confused 我用初始化UITapGestureRecognizor 的示例更新了答案。这可以用来代替touchesBegan。 Pan 和 Long Press 很相似,但这是另一个问题 :)
    • 对不起,我还是看不到代码的主体应该去哪里。函数handleTapFrom(etc...)应该在哪里声明?
    猜你喜欢
    • 2023-03-30
    • 2021-03-30
    • 2013-01-26
    • 1970-01-01
    • 2018-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多