swift 如何在SceneKit中渲染用户点击位置的球体?

2g32fytz  于 2023-06-21  发布在  Swift
关注(0)|答案(1)|浏览(122)

我正在使用Swift和SceneKit开发iOS应用程序。当用户在屏幕上点击时,我想在用户刚刚点击的位置渲染一个点。我该怎么做?
我正在使用unprojectPoint()方法,但我的对象没有呈现在预期的位置。
我有一个SceneView,相机是这样的:

cameraNode.position = SCNVector3(x: 0, y: 0, z: 15)

然后我在点击位置渲染点,如下所示:

func handleTap(_ gestureRecognize: UIGestureRecognizer) {
    // retrieve the SCNView
    let scnView = self.view as! SCNView
    
    // create dot
    let geo = SCNSphere(radius: CGFloat(0.1))
    geo.firstMaterial?.diffuse.contents = UIColor.red
    let dotNode = SCNNode(geometry: geo)
    
    let p = gestureRecognize.location(in: scnView)
    let uP = scnView.unprojectPoint(SCNVector3(p.x, p.y, 5))
    // HERE - how to set position for the dot ?
    dotNode.position = SCNVector3(uP.x, uP.y, 5)
    
    scnView.scene?.rootNode.addChildNode(dotNode)
}

以下是我的Github repo:https://github.com/rudyhuynh/SceneKitExample

iezvtpos

iezvtpos1#

取消点投影

要在预期位置渲染点节点,请使用以下方法。别忘了你是在透视投影下看这个场景的。取消投影Z坐标为0.0的点将返回near clipping plane上的点。取消投影Z坐标为1.0的点将返回far clipping plane上的点。

import SceneKit

class GameViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()            
        let sceneView = self.view as! SCNView
        sceneView.scene = SCNScene()
        sceneView.backgroundColor = UIColor.black
                
        let cameraNode = SCNNode()
        cameraNode.camera = SCNCamera()
        cameraNode.simdPosition = simd_float3(0, 0, 1)
        sceneView.scene?.rootNode.addChildNode(cameraNode)
        
        let tapGesture = UITapGestureRecognizer(target: self,
                                                action: #selector(tap))
        sceneView.addGestureRecognizer(tapGesture)
    }

    @objc func tap(_ gestureRecognizer: UITapGestureRecognizer) {
        let scnView = self.view as! SCNView
        
        let geo = SCNSphere(radius: 0.01)
        geo.firstMaterial?.diffuse.contents = UIColor.white
        let dotNode = SCNNode(geometry: geo)

        let point = gestureRecognizer.location(in: scnView)
        let unprojected = scnView.unprojectPoint(.init(point.x, point.y, 0))
 
        dotNode.position = SCNVector3(unprojected.x, unprojected.y, -0.01)
        scnView.scene?.rootNode.addChildNode(dotNode)
    }
}

要在正交投影中运行摄影机,请用途:

cameraNode.camera?.usesOrthographicProjection = true

相关问题