android:方位角问题取决于初始设备倾斜

mo49yndu  于 2021-07-12  发布在  Java
关注(0)|答案(1)|浏览(389)

我目前正在编写一个android ar应用程序,我有一个问题,我的方位角计算取决于初始设备倾斜。
我用旋转矢量传感器得到方位角,高度和倾斜。
当我启动我的应用程序,手机是垂直于地面,我有良好的方位从北方。当我启动应用程序,手机与地面平行时,我的价值观不好。我也有奇怪的价值观,当我改变设备倾斜。
这是我的密码:

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);
        ...
    }
}
laik7k3q

laik7k3q1#

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

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);
            }
        }
    };

}

来源

相关问题