iosswiftscenekitskscene

How to determine if an ScnNode is left or right of the view direction of a camera node in SceneKit


I have a camera in the center of SceneKit scene at position(0,0,0) I'm rotation the camera around the y-axis to show different parts of the scene.

I want to show arrows at the left/right side of my screen to show in which direction the user has to move to view a target object.

How can I calculate if a ScnNode is positioned at the left of right side of my view direction?

enter image description here

I know:


Solution

    1. Calculate the vector to the node relative to the camera. Calculate the vector by subtracting the camera position from the node position
    2. Use atan2 to convert the vector into an angle. The Apple docs are bit thin on explanation. There's a tutorial on raywenderlich.com.

    E.g.

    let v = CGPoint(x: nodePosition.x - cameraPosition.x, y: nodePosition.y - cameraPosition.y);
    let a = atan2(v.y, v.x) // Note: order of arguments
    

    The angle is in radians, and will range between -π and π (-180 to 180 degrees). If the value is negative the node is to the left of the camera vector, positive values mean the node is to the right, and zero means the node is straight ahead.

    Conveniently, you can use this angle as-is to actually perform the rotation if you want. Just increment the camera angle by some fraction of the angle to the node.

    E.g.

    cameraRotation += a * 0.1
    

    Caveats: