我想要创建一个示例应用程序,当用户点击它时,它允许用户获取关于全球大陆的信息。为了做到这一点,我需要找出用户点击场景中的SCNSphere对象(SceneKit)的位置。我试图这样做:
import UIKit
import SceneKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let scene = SCNScene()
/* Lighting and camera added (hidden)*/
let earthNode = SCNSphere(radius: 1)
/* Added styling to the Earth (hidden)*/
earthNode.name = "Earth"
scene.rootNode.addChildNode(earthNode)
let sceneView = self.view as! SCNView
sceneView.scene = scene
sceneView.allowsCameraControl = true
// add a tap gesture recognizer
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTap(_:)))
sceneView.addGestureRecognizer(tapGesture)
}
@objc func handleTap(_ gestureRecognize: UIGestureRecognizer) {
// retrieve the SCNView
let sceneView = self.view as! SCNView
// check what nodes are tapped
let p = gestureRecognize.location(in: scnView)
let hitResults = sceneView.hitTest(p, options: [:])
// check that we clicked on at least one object
if hitResults.count > 0 {
// retrieved the first clicked object
let result: SCNHitTestResult = hitResults[0]
print(result.node.name!)
print("x: \(p.x) y: \(p.y)") // <--- THIS IS WHERE I PRINT THE COORDINATES
}
}
}但是,当我实际运行这段代码并点击我的球体上的一个区域时,它打印出屏幕上点击的坐标,而不是我点击的球体的位置。例如,当我点击球体的中心时,坐标是相同的,当我旋转球体后再次点击它的中心。
我想知道在实际的球体上我按下的位置,而不仅仅是点击屏幕的位置。解决这个问题最好的办法是什么?
发布于 2019-01-28 21:26:12
在hitResult中,您可以得到result.textureCoordinates,它告诉您地图纹理中的要点。从这一点开始,你应该知道你的地图的位置,因为地图应该有坐标映射到纹理。
@objc func handleTap(_ gestureRecognize: UIGestureRecognizer) {
// retrieve the SCNView
let sceneView = self.view as! SCNView
// check what nodes are tapped
let p = gestureRecognize.location(in: scnView)
let hitResults = sceneView.hitTest(p, options: [:])
// check that we clicked on at least one object
if hitResults.count > 0 {
// retrieved the first clicked object
let result: SCNHitTestResult = hitResults[0]
print(result.node.name!)
print(result.textureCoordinates(withMappingChannel 0)) // This line is added here.
print("x: \(p.x) y: \(p.y)") // <--- THIS IS WHERE I PRINT THE COORDINATES
}
}https://stackoverflow.com/questions/54409801
复制相似问题