Search code examples
swiftvectorlinearkit

How to create lines with start and end points in Swift (ARKit, SCNKit)


I want to create a line that I can tell it where to start and where to end in a Scene in ARKit. Someone else made this class but I get errors. Something simple like startLine at node... and endLine at node... would be helpful. I feel like it shouldn't be so complicated to do a simple line between two points so if your answer is complicated please explain why it has to be. Thank you all for your help!

class LineNode: SCNNode {

private(set) var cylinder: SCNCylinder
private(set) var positionA: SCNVector3
private(set) var positionB: SCNVector3

init(with startingPoint: SCNVector3, endPoint: SCNVector3, radius: Float = 0.02, color: UIColor = .red) {
    self.positionA = startingPoint
    self.positionB = endPoint
    let vector = endPoint - startingPoint  *//error*
    let height = vector.length()
    cylinder = SCNCylinder(radius: radius, height: Float(height))
    cylinder.radialSegmentCount = 8
    cylinder.firstMaterial?.diffuse.contents = color
    super.init()
    geometry = cylinder
    position = (endPoint + startingPoint) / 2   *//error*
    eulerAngles = SCNVector3.lineEulerAngles(vector: vector)
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
  }
}

// I get the error:Binary operator '-' cannot be applied to two 'SCNVector3' operands


Solution

  • You need to write an extension if you want to use '+/-' on a Vector. Just paste this under the class defintion.

    class ... {
     // class code
    }
    func + (left: SCNVector3, right: SCNVector3) -> SCNVector3 {
        return SCNVector3Make(left.x + right.x, left.y + right.y, left.z + right.z)
    }
    
    func - (left: SCNVector3, right: SCNVector3) -> SCNVector3 {
        return SCNVector3Make(left.x - right.x, left.y - right.y, left.z - right.z)
    }
    

    post it below the class bracket