Draw SceneKit object between two points

前端 未结 7 1995
别跟我提以往
别跟我提以往 2020-12-07 23:51

Having made some progress in the geometry side of things I\'m moving on to putting together an entire scene. That scene has a couple dozen objects, each defined by a boundin

7条回答
  •  借酒劲吻你
    2020-12-08 00:15

    Here's a solution using simd and quaternions for the rotation. I based the extension off of the answer by @Bersaelor.

    I used this derivation (https://stackoverflow.com/a/1171995/6693924) to create the quaternion from two vectors. Hope this helps.

    extension SCNNode {
        static func lineNode(from: simd_float3, to: simd_float3, radius : CGFloat = 0.25) -> SCNNode
        {
            let vector = to - from
            let height = simd_length(vector)
    
            //cylinder
            let cylinder = SCNCylinder(radius: radius, height: CGFloat(height))
            cylinder.firstMaterial?.diffuse.contents = UIColor.white
    
            //line node
            let lineNode = SCNNode(geometry: cylinder)
    
            //adjust line position
            let line_axis = simd_float3(0, height/2, 0)
            lineNode.simdPosition = from + line_axis
    
            let vector_cross = simd_cross(line_axis, vector)
            let qw = simd_length(line_axis) * simd_length(vector) + simd_dot(line_axis, vector)
            let q = simd_quatf(ix: vector_cross.x, iy: vector_cross.y, iz: vector_cross.z, r: qw).normalized
    
            lineNode.simdRotate(by: q, aroundTarget: from)
            return lineNode
        }
    }
    

提交回复
热议问题