两点之间的SceneKit对象

mjr*_*der 1 scenekit swift

给定3D(a,b)和SCNCapsule,SCNTorus,SCNTube等中的2个点,如何定位对象,以便对象从a点开始到b点结束?

Swift或Objective-C中的代码示例将不胜感激.

从Moustachs回答我设法做了一个二维解决方案:

var v1 = SCNVector3(x: Float(a.x), y: Float(a.y), z: 0.0)
var v2 = SCNVector3(x: Float(b.x), y: Float(b.y), z: 0.0)

let height = CGFloat(v1.distance(v2))
var capsule = SCNCapsule(capRadius: 0.1, height: height)

var node = SCNNode(geometry: capsule)

var midpoint = (v1 + v2) / 2.0

node.position = midpoint

var rotp = v2 - midpoint

let rotx = atan2( rotp.y, rotp.x )
node.eulerAngles = SCNVector3Make(0.0, 0.0, rotx)

self.addChildNode(node)
Run Code Online (Sandbox Code Playgroud)

我知道,对于完整的3D旋转,有无数的解决方案,但我不关心第三轴.尽管如此,似乎即使是第二轴旋转也不适合我.也许我的数学逃避了我.任何人都可以告诉我如何将这些代码提升到3D空间?

(我正在使用Swift和Kim Pedersens SCNVector3Extensions:https://github.com/devindazzle/SCNVector3Extensions)

E. *_*oux 7

我给你带来了好消息!你可以链接两个点并在这个Vector上放一个SCNNode!

拿这个,享受两点之间的画线!

class   CylinderLine: SCNNode
{
    init( parent: SCNNode,//Needed to line to your scene
        v1: SCNVector3,//Source
        v2: SCNVector3,//Destination
        radius: CGFloat,// Radius of the cylinder
        radSegmentCount: Int, // Number of faces of the cylinder
        color: UIColor )// Color of the cylinder
    {
        super.init()

        //Calcul the height of our line
        let  height = v1.distance(v2)

        //set position to v1 coordonate
        position = v1

        //Create the second node to draw direction vector
        let nodeV2 = SCNNode()

        //define his position
        nodeV2.position = v2
        //add it to parent
        parent.addChildNode(nodeV2)

        //Align Z axis
        let zAlign = SCNNode()
        zAlign.eulerAngles.x = CGFloat(M_PI_2)

        //create our cylinder
        let cyl = SCNCylinder(radius: radius, height: CGFloat(height))
        cyl.radialSegmentCount = radSegmentCount
        cyl.firstMaterial?.diffuse.contents = color

        //Create node with cylinder
        let nodeCyl = SCNNode(geometry: cyl )
        nodeCyl.position.y = CGFloat(-height/2)
        zAlign.addChildNode(nodeCyl)

        //Add it to child
        addChildNode(zAlign)

        //set constraint direction to our vector
        constraints = [SCNLookAtConstraint(target: nodeV2)]
    }

    override init() {
        super.init()
    }
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
}

private extension SCNVector3{
    func distance(receiver:SCNVector3) -> Float{
        let xd = receiver.x - self.x
        let yd = receiver.y - self.y
        let zd = receiver.z - self.z
        let distance = Float(sqrt(xd * xd + yd * yd + zd * zd))

        if (distance < 0){
            return (distance * -1)
        } else {
            return (distance)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)