Getting OpenGL camera forward vector from Android ensors

Viewed 29

How can I get a direction vector representing the direction the back of the device is pointing relative to world coordinates from sensor data?

Registering for events:

fun attach() {
    sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)?.let {
        sensorManager.registerListener(this, it, SAMPLING, REPORTING)
    }
    sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD)?.let {
        sensorManager.registerListener(this, it, SAMPLING, REPORTING)
    }
}

Storing values:

override fun onSensorChanged(event: SensorEvent) {
    if (event.sensor.type == Sensor.TYPE_ACCELEROMETER) {
        accelerometerReading[0] = event.values[0]
        accelerometerReading[1] = event.values[1]
        accelerometerReading[2] = event.values[2]
    } else if (event.sensor.type == Sensor.TYPE_MAGNETIC_FIELD) {
        magnetometerReading[0] = event.values[0]
        magnetometerReading[1] = event.values[1]
        magnetometerReading[2] = event.values[2]
    }
    updateDirection()
}

Updating the direction in native code:

private fun updateDirection() {
    getRotationMatrix(rotationMatrix, null, accelerometerReading, magnetometerReading)
    Matrix.multiplyMV(direction, 0, rotationMatrix, 0, forward, 0)

    filteredX = direction[0].filter(filteredX)
    filteredY = direction[1].filter(filteredY)
    filteredZ = direction[2].filter(filteredZ)

    nativeApi.onCameraDirection(filteredX, filteredY , filteredZ)
}
private val forward = floatArrayOf(0.0f, 0.0f, -1.0f, 0.0f)
private fun Float.filter(old: Float) = old * 0.8 + this * 0.2

I am trying to grab the rotation matrix according to sensors, and then I am transforming the forward vector (0, 0, -1) in OpenGL coordinate system into the world coordinate system.

I've been reading the API all day and tried an endless amount of code snippets, but still have issues with the resulting vector.

0 Answers
Related