【问题标题】:SpriteKit: node Y position and touch Y position not consistentSpriteKit:节点Y位置和触摸Y位置不一致
【发布时间】:2014-12-27 02:40:25
【问题描述】:

对 SpriteKit 和 iOS 开发来说是全新的。我正在学习一个非常基本的 SpriteKit 教程,并注意到当在与节点。例如:

import SpriteKit

class GameScene: SKScene {

  override func didMoveToView(view: SKView) {
    // add a text label at X: 100 and Y: 100
    let labelNode = SKLabelNode(text: "X:100 Y:100")
    labelNode.position.x = 100
    labelNode.position.y = 100
    labelNode.fontSize = 20.0
    addChild(labelNode)
  }

  override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
    // for each touch, print the X and Y positions
    for touch: AnyObject in touches {
      println("You touched at X: \(touch.locationInView(self.view!).x) and Y: \(touch.locationInView(self.view!).y)")
    }
  }

}

这会在场景左下角的 X:100 和 Y:100 处添加文本(使用默认的 scene.anchorPoint)。当您触摸时,它会打印您触摸的位置的 X 和 Y。

奇怪的是,当我触摸到标签节点的中心时,我触摸到的1.)节点和2.)的X位置是一致的。但Y不是。节点的 Y 是 100,而触摸的 Y 是 266。请看下面的截图:

谁能解释这是为什么?

【问题讨论】:

    标签: ios swift sprite-kit


    【解决方案1】:

    我相信这里的罪魁祸首是locationInView(),它返回底层视图坐标空间中的一个位置,它使用不同的坐标系作为您的场景/节点。使用locationInNode() 应该可以解决这个问题。

    来自the documentation:

    返回接收器在给定节点坐标系中的当前位置。

    如下使用:

    println("You touched at X: \(touch.locationInNode(self).x) and Y: \(touch.locationInNode(self).y)")
    

    【讨论】:

    • 谢谢!作为后续问题:在touch.locationInNode(self).x 中,self 指的是哪个类?
    • 文档说它需要一个 SKNode 的实例。 self 和 SKNode 怎么样?
    • @imderek 当然可以。在这种情况下,self 指的是您的场景(SKScene 的实例),它是 SKEffectNode 的子类,SKNode 的子类。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-28
    • 1970-01-01
    • 2014-09-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多