我正在使用 SKTileMaps 和 CameraNode 以及 GameplayKit 和 SpriteKit
我想要工作的代码不正确在“ 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/