How do I get the forward (LookAt) vector of the camera in ARKit?

Viewed 255

I am trying to get the forward (LookAt) vector of the camera in ARKit, but I think I getting something wrong.

After doing some research, I wrote this helper extension below, but I don't think it is right from the data I am getting. (The Y-Component is negative when I point the camera upwards).

Can someone let me know what I getting wrong about getting the vector the camera is pointing in world space? Also, if there is a better way to get it (CoreLocation?) I am open to that too.

extension ARCamera {
    /**
    The Camera forward orientation vector as vector_float3.
    */
    var forward: vector_float3 {
        get {
            return vector_float3(-1 * self.transform.columns.3.x,
                                 -1 * self.transform.columns.3.y,
                                 -1 * self.transform.columns.3.z)
        }
    }

    /**
    The Camera forward orientation vector as vector_float3 normalized.
    */
    var normalForward: vector_float3 {
        get {
            let theNormaled = simd_normalize(vector_float3(-1 * self.transform.columns.3.x,
                                                           -1 * self.transform.columns.3.y,
                                                           -1 * self.transform.columns.3.z))
            return theNormaled
        }
    }
}

Thanks in advance.

Stan

2 Answers
public extension float4x4 {

    var forwardVector: simd_float3 { simd_float3(columns.2.x, columns.2.y, columns.2.z).normalized() }

}


public extension simd_float3 {
    
    /**
     * Negates the vector described by simd_float3 and returns
     * the result as a new simd_float3.
     */
    func negate() -> simd_float3 {
        return self * -1
    }
    
    /**
     * Returns the length (magnitude) of the vector described by the simd_float3
     */
    func magnitude() -> Float {
        return sqrtf(x*x + y*y + z*z)
    }
    
    /**
     * Normalizes the vector described by the simd_float3 to length 1.0 and returns
     * the result as a new simd_float3.
     */
    public func normalized() -> simd_float3 {
        return self / magnitude()
    }
}

I think I found a better way.

I created a raycastQuery, and just used the point in the middle of the ARSCNView as the origin point. The direction is a property of the raycast Result.

It still doesn't seem like the correct way, (I feel I should be able to pull the forward vector from the Camera's transform property, but this seems to work.

Related