【问题标题】:Getting location of tap on SCNSphere - Swift (SceneKit) / iOS在 SCNSphere 上获取点击位置 - Swift (SceneKit) / iOS
【发布时间】:2019-06-21 21:59:53
【问题描述】:

我想创建一个示例应用程序,允许用户在点击地球上的大陆时获取有关大陆的信息。为了做到这一点,我需要找出用户在场景(SceneKit)中点击 SCNSphere 对象的位置。我试图这样做:

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


        }
    }

}

但是,当我实际运行此代码并单击球体上的某个区域时,它会在屏幕上打印出点击的坐标,而不是我在球体上点击的位置。例如,当我点击球体的中心时,坐标是相同的,当我在旋转球体后再次点击球体的中心时。

我想知道我在实际球体上按下的位置,而不仅仅是我在屏幕上单击的位置。我应该解决这个问题的最佳方法是什么?

【问题讨论】:

    标签: ios swift uigesturerecognizer scenekit scnsphere


    【解决方案1】:

    在 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
    
    
        }
    }
    

    【讨论】:

    • 感谢您的快速回复,效果很好!
    • 太棒了!您只是缺少一个 : 在 withMappingChannel 之后
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-01
    • 2020-11-29
    • 2018-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多