4

以下代码将节点放置在相机前面,但始终位于距离相机位置 10 厘米的中心。我想将节点放置在距离 z 方向 10cm 处,但在我触摸屏幕的 x 和 y 坐标处。所以触摸屏幕的不同部分应该会导致一个节点被放置在相机前面 10cm 处,但在触摸的 x 和 y 位置,而不是总是在中心。

    var cameraRelativePosition = SCNVector3(0,0,-0.1)
    let sphere = SCNNode()
    sphere.geometry = SCNSphere(radius: 0.0025)
    sphere.geometry?.firstMaterial?.diffuse.contents = UIColor.white      
    Service.addChildNode(sphere, toNode: self.sceneView.scene.rootNode,    
    inView: self.sceneView, cameraRelativePosition:  
    cameraRelativePosition)

服务.swift

class Service: NSObject {

  static func addChildNode(_ node: SCNNode, toNode: SCNNode, inView:     
  ARSCNView, cameraRelativePosition: SCNVector3) {

    guard let currentFrame = inView.session.currentFrame else { return }
    let camera = currentFrame.camera
    let transform = camera.transform
    var translationMatrix = matrix_identity_float4x4
    translationMatrix.columns.3.x = cameraRelativePosition.x
    translationMatrix.columns.3.y = cameraRelativePosition.y
    translationMatrix.columns.3.z = cameraRelativePosition.z
    let modifiedMatrix = simd_mul(transform, translationMatrix)
    node.simdTransform = modifiedMatrix
    toNode.addChildNode(node)
  }
}

结果应该看起来像这样:https ://justaline.withgoogle.com

4

1 回答 1

2

我们可以使用(并且都符合这个协议) 的方法将屏幕上的一个点转换为一个 3D 点unprojectPoint(_:)。当点击屏幕时,我们可以这样计算射线:SCNSceneRendererSCNViewARSCNView

func getRay(for point: CGPoint, in view: SCNSceneRenderer) -> SCNVector3 {
    let farPoint  = view.unprojectPoint(SCNVector3(Float(point.x), Float(point.y), 1))
    let nearPoint = view.unprojectPoint(SCNVector3(Float(point.x), Float(point.y), 0))

    let ray = SCNVector3Make(farPoint.x - nearPoint.x, farPoint.y - nearPoint.y, farPoint.z - nearPoint.z)

    // Normalize the ray
    let length = sqrt(ray.x*ray.x + ray.y*ray.y + ray.z*ray.z)

    return SCNVector3Make(ray.x/length, ray.y/length, ray.z/length)
}

射线的长度为 1,因此通过将其乘以 0.1 并添加相机位置,我们得到您正在搜索的点。

于 2018-04-24T10:28:23.860 回答