Draw SceneKit object between two points

前端 未结 7 2010
别跟我提以往
别跟我提以往 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:21

    Sprout's (wow, the autocorrect will not allow me to actually type in his name!) post is indeed a solution, but I have implemented a very different solution in my code.

    What I do is calculate the length of the line and the two endpoints, based on the X, Y and Z locations from the two ends:

    let w = SCNVector3(x: CGFloat(x2m-x1m), y: CGFloat(y2m-y1m), z: CGFloat(z2m-z1m))
    let l = w.length()
    

    The length is simply pythag. Now I make an SCNNode that will hold the SCNCylinder, and position it in the middle of the line:

        let node = SCNNode(geometry: cyl)
        node.position = SCNVector3(x: CGFloat((x1m+x2m)/2.0), y: CGFloat((y1m+y2m)/2.0), z: CGFloat((z1m+z2m)/2.0))
    

    And now the nasty part, where we calculate the Euler angles and rotate the node:

        let lxz = (Double(w.x)**2 + Double(w.z)**2)**0.5
        var pitch, pitchB: Double
        if w.y < 0 {
            pitchB = M_PI - asin(Double(lxz)/Double(l))
        } else {
            pitchB = asin(Double(lxz)/Double(l))
        }
        if w.z == 0 {
            pitch = pitchB
        } else {
            pitch = sign(Double(w.z)) * pitchB
        }
        var yaw: Double
        if w.x == 0 && w.z == 0 {
            yaw = 0
        } else {
            let inner = Double(w.x) / (Double(l) * sin (pitch))
            if inner > 1 {
                yaw = M_PI_2
            } else if inner < -1 {
                yaw = M_PI_2
            } else {
                yaw = asin(inner)
            }
        }
        node.eulerAngles = SCNVector3(CGFloat(pitch), CGFloat(yaw), 0)
    

    I suspect there is a much simpler way to do this using one of the other rotation inputs, but this works and working is a feature!

提交回复
热议问题