Skip to content

Instantly share code, notes, and snippets.

@digitallysavvy
Created February 29, 2020 04:44
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save digitallysavvy/033340e342d793dec97343141ba3e7d1 to your computer and use it in GitHub Desktop.
Save digitallysavvy/033340e342d793dec97343141ba3e7d1 to your computer and use it in GitHub Desktop.
An example snippet of how to add a 3D annotation into an AR scene.
func showResult(_ result: String) {
// HIT TEST : REAL WORLD
// Get Screen Centre
let screenCentre : CGPoint = CGPoint(x: self.sceneView.bounds.midX, y: self.sceneView.bounds.midY)
let arHitTestResults : [ARHitTestResult] = sceneView.hitTest(screenCentre, types: [.featurePoint]) // Alternatively, we could use '.existingPlaneUsingExtent' for more grounded hit-test-points.
if let closestResult = arHitTestResults.first {
// Get Coordinates of HitTest
let transform : matrix_float4x4 = closestResult.worldTransform
let worldCoord : SCNVector3 = SCNVector3Make(transform.columns.3.x, transform.columns.3.y, transform.columns.3.z)
// Create 3D Text
let node : SCNNode = createNewResultsNode(result)
resultsRootNode.addChildNode(node)
node.position = worldCoord
}
}
func createNewResultsNode(_ text : String) -> SCNNode {
// Warning: Programmatically generating 3D Text is susceptible to crashing. To reduce chances of crashing; reduce number of polygons, letters, smoothness, etc.
print("shwo result: \(text)")
// Billboard contraint to force text to always face the user
let billboardConstraint = SCNBillboardConstraint()
billboardConstraint.freeAxes = SCNBillboardAxis.Y
// SCN Text
let scnText = SCNText(string: text, extrusionDepth: CGFloat(textDepth))
var font = UIFont(name: "Helvetica", size: 0.15)
font = font?.withTraits(traits: .traitBold)
scnText.font = font
scnText.alignmentMode = CATextLayerAlignmentMode.center.rawValue
scnText.firstMaterial?.diffuse.contents = UIColor.orange
scnText.firstMaterial?.specular.contents = UIColor.white
scnText.firstMaterial?.isDoubleSided = true
scnText.chamferRadius = CGFloat(textDepth)
// Text Node
let (minBound, maxBound) = scnText.boundingBox
let textNode = SCNNode(geometry: scnText)
// Centre Node - to Centre-Bottom point
textNode.pivot = SCNMatrix4MakeTranslation( (maxBound.x - minBound.x)/2, minBound.y, textDepth/2)
// Reduce default text size
textNode.scale = SCNVector3Make(0.2, 0.2, 0.2)
// Sphere Node
let sphere = SCNSphere(radius: 0.005)
sphere.firstMaterial?.diffuse.contents = UIColor.cyan
let sphereNode = SCNNode(geometry: sphere)
// Text Parent Node
let textParentNode = SCNNode()
textParentNode.addChildNode(textNode)
textParentNode.addChildNode(sphereNode)
textParentNode.constraints = [billboardConstraint]
return textParentNode
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment