ios – ARKit: Anchor Size Larger Than Visible Area in Camera in swift


I’m encountering an issue in ARKit where the anchor size, created when capturing an image and adding a red box, appears to be much larger than the visible area in the camera. I’m using the following code to create the box:

 func createBox(hit:ARHitTestResult, isLandscape:Bool) -> SCNNode {
        let dimensions = calculateVisibleSize(hitTestResult: hit)

      var box : SCNBox = SCNBox(width: (dimensions.width/2) , height: dimensions.height, length: 0.05, chamferRadius:0)
        
        if isLandscape {
            box = SCNBox(width: dimensions.height, height: (dimensions.width/2) , length: 0.05, chamferRadius:0)
        }
        
        let boxNode = SCNNode(geometry: box)
        boxNode.physicsBody = SCNPhysicsBody(type: .static, shape: SCNPhysicsShape(geometry: box, options: nil))
        boxNode.geometry?.firstMaterial?.diffuse.contents = UIColor.red.withAlphaComponent(0.7)
    
        }

     func calculateVisibleSize(hitTestResult: ARHitTestResult) -> CGSize {
        guard let currentFrame = arView.session.currentFrame else { return CGSize(width: 0, height: 0) }
        
        let rayFrom = simd_float3(currentFrame.camera.transform.columns.3.x,
                                  currentFrame.camera.transform.columns.3.y,
                                  currentFrame.camera.transform.columns.3.z)
        
        let rayTo = simd_float3(rayFrom.x, rayFrom.y, rayFrom.z - 0.1) // Slightly below the camera
        
        let screenPosition = arView.projectPoint(SCNVector3(rayTo.x, rayTo.y, rayTo.z))
        let screenPoint = CGPoint(x: CGFloat(screenPosition.x), y: CGFloat(screenPosition.y))
        
        let planeDimensions = calculateDistance(from: rayFrom, to: hitTestResult.worldTransform, camera: currentFrame.camera)
        
        return planeDimensions
    }

The calculateVisibleSize function is intended to determine the size of the box based on the camera’s perspective. However, it seems that the anchor size doesn’t match the visible area as expected. If i use a distance of 140 to 160 cm, it works fine.

Any insights on why the anchor size might be off or suggestions for adjustments to ensure the anchor aligns with the visible area in the camera would be greatly appreciated.

Thanks in advance!

Latest articles

spot_imgspot_img

Related articles

Leave a reply

Please enter your comment!
Please enter your name here

spot_imgspot_img