简体   繁体   中英

Draw straight line from start value to end value ARKit

As always I need your help. I need to draw a straight line from a start value (declared as SCNVector3 ) and connected to the position in the real world till the end point.

Can someone explain to me with some lines of code how can I do it? Thank you!

You'll need to implement: touchesBegan , touchesMoved , touchesEnded , touchesCancelled for your camera view controller. In touchesBegan you will need to make hitTest for current ARFrame in the UITouch location. Then you'll have your startPosition and your lastTouch , which is your start UITouch .

Then you will need to add timer with 0.016_667 interval (60Hz) which will update your last touch position with hitTest when you camera moves. Same you'll do in touchesMoved function. And in touchesMoved you'll also update your lastTouch . So at this point you'll have your startPosition and currentPosition , which is SCNVector3 . And you can just redraw SCNCylinder (with 0.001m radius for example) for those positions if you need straight line.

At last step in touchesEnded you'll fix your line, or if touchesCancelled you will remove it and clear lastTouch .

UPD

If you need 2D line on the screen, then you'll need to use projectPoint for your ARSceneView.

3D line drawing

For drawing 3D line you could SCNGeometry use extension:

extension SCNGeometry {
    class func line(from vector1: SCNVector3, to vector2: SCNVector3) -> SCNGeometry {
        let indices: [Int32] = [0, 1]
        let source = SCNGeometrySource(vertices: [vector1, vector2])
        let element = SCNGeometryElement(indices: indices, primitiveType: .line)
        return SCNGeometry(sources: [source], elements: [element])
    }
}

Using:

let line = SCNGeometry.line(from: startPosition, to: endPosition)
let lineNode = SCNNode(geometry: line)
lineNode.position = SCNVector3Zero
sceneView.scene.rootNode.addChildNode(lineNode)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM