MiguelSlv
MiguelSlv

Reputation: 15123

SCNScene: Calculate projected size of an object

My game has a scene and HUD (SKScene) as in most games. To avoid overlap with HUD elements, I need to calculate the projected size of my main object. Because the HUD dimensions and projected size of the object are different for each iPhone model, I need a way to do this dynamically, and for that I need to get the projected size of my main object.

The obvious approach for me was to use the xFov and yFov, but for some reason they are always zero. usesOrthographicProjection is set to false so it's not because of that.

Below a simple test code that trys to equal the plane of the scene with the plane on the HUD.

import UIKit
import QuartzCore
import SceneKit
import SpriteKit

class GameViewController: UIViewController {

    var hud:SKScene!

    override func viewDidLoad() {
        super.viewDidLoad()

        // create a new scene
        let scene = SCNScene()

        // create and add a camera to the scene
        let cameraNode = SCNNode()
        cameraNode.camera = SCNCamera()
        scene.rootNode.addChildNode(cameraNode)
        cameraNode.position = SCNVector3(x: 0, y: 0, z: 10)

        // retrieve the SCNView
        let scnView = self.view as SCNView

        // set the scene to the view
        scnView.scene = scene

        let sCPlaneGeo = SCNPlane(width: 5, height: 5)
        let sCPlane = SCNNode(geometry: sCPlaneGeo)
        scene.rootNode.addChildNode(sCPlane)

        hud = SKScene(size: view.bounds.size)
        scnView.overlaySKScene = hud


        let sKplane = SKShapeNode(rectOfSize: CGSizeMake(50, 50))
        sKplane.lineWidth = 1
        sKplane.position = CGPointMake(view.bounds.size.width/2, view.bounds.size.height/2)
        sKplane.strokeColor = UIColor.redColor()

        hud.addChild(sKplane)

        println(cameraNode.camera?.xFov) //Prints Zero

    }

}

Upvotes: 1

Views: 2562

Answers (1)

rickster
rickster

Reputation: 126127

  1. Use getBoundingBoxMin(_:max:) to find the corners of the space your 3D element occupies in the SceneKit scene.

  2. Use projectPoint to convert those points from 3D scene coordinates to 2D view coordinates.

  3. Use convertPointFromView to convert from (UIKit) view coordinates to your SpriteKit scene's coordinate system.

From the points in step 3 you can construct a rectangle or other shape for your HUD elements to avoid.

Upvotes: 9

Related Questions