我目前正在编写一个Android AR应用程序,我的方位角计算存在问题,具体取决于初始设备倾斜度。

我使用ROTATION_VECTOR传感器获取方位角,高度和倾斜度。

当我启动应用程序并且手机与地面垂直时,我从北方获得了良好的方位角。当我启动该应用程序并且电话与地面平行时,我的值不正确。更改设备倾斜度时,我的值也很奇怪。

这是我的代码:

public void onSensorChanged(SensorEvent event)
{
    if (event.sensor.getType() == sensor.TYPE_ROTATION_VECTOR)
    {
        SensorManager.getRotationMatrixFromVector(rotationVectorMatrix, event.values);
        SensorManager.remapCoordinateSystem(rotationVectorMatrix, SensorManager.AXIS_X, SensorManager.AXIS_Z, rotationMatrix);
        SensorManager.getOrientation(rotationMatrix, orientation);
        ...
    }
}

最佳答案

要获取方位角,可以使用加速度计和磁场传感器。您可以使用以下代码记录方位角值。

    public class MainActivity extends AppCompatActivity {

    private int mAzimuth = 0; // degree

    private SensorManager mSensorManager = null;

    private Sensor mAccelerometer;
    private Sensor mMagnetometer;

    boolean haveAccelerometer = false;
    boolean haveMagnetometer = false;

    @Override
    protected void onCreate( Bundle savedInstanceState ) {
        super.onCreate(savedInstanceState);

        mSensorManager = (SensorManager) getSystemService(Service.SENSOR_SERVICE);

        this.mAccelerometer = this.mSensorManager.getDefaultSensor( Sensor.TYPE_ACCELEROMETER );
        this.haveAccelerometer = this.mSensorManager.registerListener( mSensorEventListener, this.mAccelerometer, SensorManager.SENSOR_DELAY_GAME );

        this.mMagnetometer = this.mSensorManager.getDefaultSensor( Sensor.TYPE_MAGNETIC_FIELD );
        this.haveMagnetometer = this.mSensorManager.registerListener( mSensorEventListener, this.mMagnetometer, SensorManager.SENSOR_DELAY_GAME );

        if ( haveAccelerometer && haveMagnetometer ) {
            // ready to go
        } else {
            // unregister and stop
        }

    }

    private SensorEventListener mSensorEventListener = new SensorEventListener() {

        float[] gData = new float[3]; // accelerometer
        float[] mData = new float[3]; // magnetometer
        float[] rMat = new float[9];
        float[] iMat = new float[9];
        float[] orientation = new float[3];

        public void onAccuracyChanged(Sensor sensor, int accuracy ) {}

        @Override
        public void onSensorChanged( SensorEvent event ) {
            float[] data;
            switch ( event.sensor.getType() ) {
                case Sensor.TYPE_ACCELEROMETER:
                    gData = event.values.clone();
                    break;
                case Sensor.TYPE_MAGNETIC_FIELD:
                    mData = event.values.clone();
                    break;
                default: return;
            }

            if ( SensorManager.getRotationMatrix( rMat, iMat, gData, mData ) ) {
                mAzimuth= (int) ( Math.toDegrees( SensorManager.getOrientation( rMat, orientation )[0] ) + 360 ) % 360;
                Log.d("AzimuthTag", "Azimuth:"+mAzimuth);
            }
        }
    };

}


Source

09-16 04:54