Scene Kit: projectPoint calculated is displaced

2.7k views Asked by At

I am trying do draw an frame over a sphere on the parent view of the scene, but for some reason the points converted by SCNScene.projectPoint method are displaced.

To make it simple, i created a sphere at the center of the scene with 2 radius. The sphere is attached to the root node, so top left corner on world coordinates is at (-2,-2,0) point.

Here the complete code:

func sphereWithFrame(){

    var v1 = SCNVector3(x: 0,y: 0,z: 0)
    var v2 = SCNVector3(x: 0,y: 0,z: 0)

    let topSphere = SCNSphere(radius: 2.0)
    topSphere.firstMaterial!.diffuse.contents = UIColor.greenColor()


    let topSphereNode = SCNNode(geometry: topSphere)
    topSphereNode.position = SCNVector3Make(0, 0, 0)
    scene.rootNode.addChildNode(topSphereNode)

    topSphereNode.getBoundingBoxMin(&v1, max: &v2)

    //world coordinates
    let v1w =  topSphereNode.convertPosition(v1, toNode: scene.rootNode)
    let v2w =  topSphereNode.convertPosition(v2, toNode: scene.rootNode)

    //projected coordinates
    let v1p = scnview.projectPoint(v1w)
    let v2p = scnview.projectPoint(v2w)

    //frame rectangle
    var rect = CGRectMake(CGFloat(v1p.x), CGFloat(v2p.y), CGFloat(v2p.x - v1p.x), CGFloat(v1p.y - v2p.y))
    let rectView = UIView(frame: rect)
    rectView.alpha = 0.3
    rectView.backgroundColor = UIColor.blueColor()
    scnview.addSubview(rectView)

    println("v1 \(v1.toString()), v2\(v2.toString())")
    println("v1w \(v1w.toString()), v2w\(v2w.toString())")
    println("v1p \(v1p.toString()), v2w\(v2p.toString())")
    println("rect\(rect)")

}

The console:

v1 x:-2.0,y:-2.0,z:-2.0, v2x:2.0,y:2.0,z:2.0
v1w x:-2.0,y:-2.0,z:-2.0, v2wx:2.0,y:2.0,z:2.0
v1p x:90.718,y:309.282,z:0.925926, v2wx:263.923,y:136.077,z:0.883838
rect(90.718, 136.077, 173.205, 173.205)

The result on screen is a rectangle a little to the up right from where should be. The result on screen

I try to follow the post " How do I find my mouse point in a scene using SceneKit?". What am i getting wrong?

1

There are 1 answers

1
MiguelSlv On BEST ANSWER

have to set z to zero on both world coordinates:

v1w.z = 0
v2w.z = 0

explaining things help