1
votes

I am trying to draw a line between two custom SCNNode points using ARKit. I am using this code https://github.com/TBXark/Ruler

Whenever I draw a line and move away from iPhone device while pointing at the line, its thickness changes. Also in 40% of cases, line breaks up and disappear from the node points.

I have already tried using multiple methods for this but still not getting the desired result.

I want the line to stay stationary between the points and not change in width as I move iPhone away from it. I want to behave it similar to "iOS Measure App" .

1

1 Answers

1
votes

Use the following code to draw a line (as a Cylinder primitive) between two SCNNodes:

extension SCNGeometry {

    class func cylinderLine(from: SCNVector3, to: SCNVector3, segments: Int) -> SCNNode {

        let x1 = from.x
        let x2 = to.x

        let y1 = from.y
        let y2 = to.y

        let z1 = from.z
        let z2 = to.z

        let distance = sqrtf((x2 - x1) * (x2 - x1) +
                             (y2 - y1) * (y2 - y1) +
                             (z2 - z1) * (z2 - z1))

        let cylinder = SCNCylinder(radius: 0.005,
                                   height: CGFloat(distance))   

        cylinder.radialSegmentCount = segments
        cylinder.firstMaterial?.diffuse.contents = UIColor.yellow

        let lineNode = SCNNode(geometry: cylinder)

        lineNode.position = SCNVector3(((from.x + to.x)/2),
                                       ((from.y + to.y)/2),
                                       ((from.z + to.z)/2))

        lineNode.eulerAngles = SCNVector3(Float.pi/2,
                                          acos((to.z - from.z)/distance),
                                          atan2(to.y - from.y, to.x - from.x))

        return lineNode
    }
}

class ViewController: UIViewController, ARSCNViewDelegate {

    // SOME CODE .....................................

    func addLine(start: SCNVector3, end: SCNVector3) {

        let lineNode = SCNGeometry.cylinderLine(from: start, to: end, segments: 5)
        sceneView.scene.rootNode.addChildNode(lineNode)
    }
}