Drawing a line between two points using SceneKit

后端 未结 7 454
轻奢々
轻奢々 2020-12-04 20:12

I have two points (let\'s call them pointA and pointB) of type SCNVector3. I want to draw a line between them. Seems like it should be easy, but can\'t find a way to do it.<

7条回答
  •  攒了一身酷
    2020-12-04 20:53

    Here's a solution using triangles that works independent of the direction of the line. It's constructed using the cross product to get points perpendicular to the line. So you'll need a small SCNVector3 extension, but it'll probably come in handy in other cases, too.

    private func makeRect(startPoint: SCNVector3, endPoint: SCNVector3, width: Float ) -> SCNGeometry {
        let dir = (endPoint - startPoint).normalized()
        let perp = dir.cross(SCNNode.localUp) * width / 2
    
        let firstPoint = startPoint + perp
        let secondPoint = startPoint - perp
        let thirdPoint = endPoint + perp
        let fourthPoint = endPoint - perp
        let points = [firstPoint, secondPoint, thirdPoint, fourthPoint]
    
        let indices: [UInt16] = [
            1,0,2,
            1,2,3
        ]
        let geoSource = SCNGeometrySource(vertices: points)
        let geoElement = SCNGeometryElement(indices: indices, primitiveType: .triangles)
    
        let geo = SCNGeometry(sources: [geoSource], elements: [geoElement])
        geo.firstMaterial?.diffuse.contents = UIColor.blue.cgColor
        return geo
    }
    

    SCNVector3 extension:

    import Foundation
    import SceneKit
    
    extension SCNVector3
    {
        /**
         * Returns the length (magnitude) of the vector described by the SCNVector3
         */
        func length() -> Float {
            return sqrtf(x*x + y*y + z*z)
        }
    
        /**
         * Normalizes the vector described by the SCNVector3 to length 1.0 and returns
         * the result as a new SCNVector3.
         */
        func normalized() -> SCNVector3 {
            return self / length()
        }
    
        /**
          * Calculates the cross product between two SCNVector3.
          */
        func cross(_ vector: SCNVector3) -> SCNVector3 {
            return SCNVector3(y * vector.z - z * vector.y, z * vector.x - x * vector.z, x * vector.y - y * vector.x)
        }
    }
    

提交回复
热议问题