iT邦幫忙

2024 iThome 鐵人賽

DAY 10
0
Mobile Development

手機Swift性能專家系列 第 10

ARKitWorldTracking 基本應用

  • 分享至 

  • xImage
  •  

首先我們要在info裡加入相機的權限歐

    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 設置 view 的 delegate
        sceneView.delegate = self
        
        // 展示 debug 訊息(可選)
        sceneView.showsStatistics = true
        
        // 創建新的場景
        let scene = SCNScene()
        sceneView.scene = scene
        
        let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleTap(_:)))
        sceneView.addGestureRecognizer(tapGestureRecognizer)
        
        // 創建AR世界追蹤的配置
        let configuration = ARWorldTrackingConfiguration()
        
        // 啟動 session
        sceneView.session.run(configuration)
    }
    
    @objc func handleTap(_ gestureRecognizer: UITapGestureRecognizer) {
        // 獲取點擊位置
        let location = gestureRecognizer.location(in: sceneView)
        
        // 射線檢測
        let hitTestResults = sceneView.hitTest(location, types: .featurePoint)
        
        if let hitResult = hitTestResults.first {
            // 創建方塊
            let cube = SCNBox(width: 0.1, height: 0.1, length: 0.1, chamferRadius: 0)
            let cubeNode = SCNNode(geometry: cube)
            
            // 設置方塊位置
            cubeNode.position = SCNVector3(
                x: hitResult.worldTransform.columns.3.x,
                y: hitResult.worldTransform.columns.3.y,
                z: hitResult.worldTransform.columns.3.z
            )
            
            // 添加方塊到場景
            sceneView.scene.rootNode.addChildNode(cubeNode)
        }

這樣你就完成點擊畫面會產生一個方塊


上一篇
ARKit 簡介
下一篇
ARkit Face Tracking基本應用
系列文
手機Swift性能專家20
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言