ARKit – detect plane with augmented reality

Draw a grid on the floor using augmented reality and eventually place objects on it.

augmente reality, arkit, plane detection, grid
The grid on the floor placed using ARKit

Let’s see how it works

Create a new project, as usual, choose “Augmented Reality App“.

Few things to add in order to detect plane, first in viewDidLoad, add:

sceneView.autoenablesDefaultLighting = true

Next, in the viewWillAppear set in the configuration the plane detection:

configuration.planeDetection = .horizontal 

Cool, you’re are ready to detect planes.


Draw the grid on plane

Implement the ARSCNViewDelegate to draw the grid:

func renderer(_ renderer: SCNSceneRenderer, didAdd node: SCNNode, for anchor: ARAnchor) { }

Save the grid image:

And draw the grid on the screen (floor):

func renderer(_ renderer: SCNSceneRenderer, didAdd node: SCNNode, for anchor: ARAnchor) {

     // plane detected
     if anchor is ARPlaneAnchor {
         let planeAnchor = anchor as! ARPlaneAnchor
         let plane = SCNPlane(width: CGFloat(planeAnchor.extent.x), height: CGFloat(planeAnchor.extent.z))
 
         let planeNode = SCNNode()
         planeNode.position = SCNVector3(x: planeAnchor.center.x, y: 0, z: planeAnchor.center.z)
         planeNode.transform = SCNMatrix4MakeRotation(-Float.pi/2, 1, 0, 0)
 
         // add the grid as material
         let gridMaterial = SCNMaterial()
         gridMaterial.diffuse.contents = UIImage(named: "art.scnassets/grid.png")
         
         plane.materials = [gridMaterial]
         planeNode.geometry = plane
 
         // place the grid when needed
         node.addChildNode(planeNode)
     } else {
         return
     }
 } 

Enjoy.

 

Alberto Pasca

Software engineer @ Pirelli & C. S.p.A. with a strong passion for mobile  development, security, and connected things.