AR 객체의 좌표를 조작하는 방법 치트 시트

16622 단어 SceneKitSwiftARKit

카메라 50cm 앞에 놓기




guard let camera = sceneView.pointOfView else {
    return
}
let cameraPos = SCNVector3Make(0, 0, -0.5)
let position = camera.convertPosition(cameraPos, to: nil)
boxNode.position = position

스크린의 탭한 위치의 50cm 앞에 놓기




override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    guard let point = touches.first?.location(in: sceneView) else {
        return
    }
    let infrontOfCamera = SCNVector3(x: 0, y: 0, z: -0.5)

    guard let cameraNode = sceneView.pointOfView else { return }
    let pointInWorld = cameraNode.convertPosition(infrontOfCamera, to: nil)

    var screenPos = sceneView.projectPoint(pointInWorld)

    screenPos.x = Float(point.x)
    screenPos.y = Float(point.y)

    let finalPosition = sceneView.unprojectPoint(screenPos)
    boxNode.position = finalPosition
}

탭하여 평면, 수직면에 배치




수평면
수직면






configuration


let configuration = ARWorldTrackingConfiguration()
configuration.planeDetection = [.horizontal, .vertical]

touchesBegan


override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    guard let location = touches.first?.location(in: sceneView),
        let horizontalHit = sceneView.hitTest(
            location,
            types: .existingPlane
            ).first else {
                return
    }
    let column3: simd_float4 = horizontalHit.worldTransform.columns.3
    let position = SCNVector3(column3.x, column3.y, column3.z)
    boxNode.position = position
    sceneView.scene.rootNode.addChildNode(boxNode)
}

임의의 방향을 향하게



예: 카메라 방향을 향하게


guard let camera = sceneView.pointOfView else {
    return
}
boxNode.look(at: camera.position)

카메라와 같은 방향을 향해




guard let camera = sceneView.pointOfView else {
    return
}
boxNode.eulerAngles = camera.eulerAngles

카메라와 같은 높이에 놓




guard let camera = sceneView.pointOfView else {
    return
}
let cameraPos = SCNVector3Make(0, 0, -0.5)
var position = camera.convertPosition(cameraPos, to: nil)
position.y = camera.position.y // ここ
boxNode.position = position

카메라에서 발사




private func shoot(){
    guard let camera = sceneView.pointOfView else {
       return
    }
    boxNode.position = camera.position

    let targetPosCamera = SCNVector3Make(0, 0, -2)
    let target = camera.convertPosition(targetPosCamera, to: nil)
    let action = SCNAction.move(to: target, duration: 1)
    boxNode.runAction(action)
}

카메라 앞에 물체를 잡아




extension PracticeViewController: ARSCNViewDelegate {
    func renderer(_ renderer: SCNSceneRenderer, updateAtTime time: TimeInterval) {
        // このフラグをボタン等で切り替える
        if holding {
            guard let camera = sceneView.pointOfView else {
                return
            }
            let cameraPos = SCNVector3Make(0, 0, -0.5)
            let position = camera.convertPosition(cameraPos, to: nil)
            boxNode.position = position
        }
    }
}

샘플 코드



샘플 코드는 ARKit-Emperor의 Practice에 있습니다!

좋은 웹페이지 즐겨찾기