swift - Tap Gesture 和 TouchesBegan 在 View 中产生不同的位置

标签 swift sprite-kit uitapgesturerecognizer gamekit touchesbegan

我正在使用 SKTileMapsCameraNode 以及 GameplayKitSpriteKit

我想要工作的代码不正确在“ View ”中找到位置

func handleTapFrom(_ sender: UITapGestureRecognizer)
{
    let location = sender.location(in: self.view)
    if (map.contains(location))
    {
        let tRow = map.tileRowIndex(fromPosition: location)
        let tColumn = map.tileColumnIndex(fromPosition: location)
        let movePosition = map.centerOfTile(atColumn: tColumn, row: tRow)
        let moveAction = SKAction.move(to: movePosition, duration:1.0)
        cam.run(moveAction)
    }

}    

并且工作正常的代码正在 self (而不是 self.view)中查找位置,这是正确的

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) 
{
    let firstTouch = touches.first?.location(in: self)
    if (map.contains(firstTouch!))
    {
        let tRow = map.tileRowIndex(fromPosition: firstTouch!)
        let tColumn = map.tileColumnIndex(fromPosition: firstTouch!)
        let movePosition = map.centerOfTile(atColumn: tColumn, row: tRow)
        let moveAction = SKAction.move(to: movePosition, duration:1.0)
        cam.run(moveAction)
    }
}

根据位置,列和行是正确的,我遇到的问题是,即使触摸位于同一位置,两个函数的位置(xfloat、yfloat)也不同

这两段代码都在 GameScene 类中,但我不明白为什么它们的位置不同?以及如何修复点击手势,使其找到的位置与在touchesBegan中找到的位置相同。

很抱歉,如果这令人困惑或难以理解。我欢迎有机会澄清。

最佳答案

在您的 handleTapFrom 函数中,位置应来自 convertPoint

func handleTapFrom(_ sender: UITapGestureRecognizer) {
    if sender.state != .ended {
        return
    }

    let location = sender.location(in: sender.view!)
    let targetLocation = self.convertPoint(fromView: location)

    if map.contains(targetLocation) {
        // Your code here
    }
}

关于swift - Tap Gesture 和 TouchesBegan 在 View 中产生不同的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45533802/

相关文章:

ios - 如何为uiview的不同部分添加多个UITapGestureRecognizer?

xcode - 解析/Swift getObjectInBackgroundWithId 查询不起作用

iphone - 同时播放相同的声音? (快速, Sprite 套件)

ios - 保持 UNNotificationContent 几秒钟

ios - Swift:在 touchesBegan 中使用 switch 语句

image - 在 SpriteKit 游戏中图像边缘模糊

ios - UITapGestureRecognizer 与 didSelectRowAtIndexPath 并发性

swift - 如何检测对 UICollectionView 中单元格 "only for a single finger"的双击?

swift - TabBar Storyboard如何连接?

ios - 在没有 Storyboard的情况下创建和执行 segue