【问题标题】:LibGDX - check if compass needs calibrationLibGDX - 检查指南针是否需要校准
【发布时间】:2020-03-27 23:21:57
【问题描述】:

如何检查指南针是否在 LibGDX(在 Android 上)中校准良好。我已经找到了如何在原生 Android 上做到这一点:

In Android can I programmatically detect that the compass is not yet calibrated?

但无法找到是否在 LibGDX 中实现。

【问题讨论】:

    标签: libgdx compass-geolocation calibration


    【解决方案1】:

    wiki 文章 Interfacing with platform specific code 中描述了您想要的内容。 LibGDX 没有任何功能,因为它不常见而且对其他后端没有任何意义。

    core 模块中,您将拥有如下内容:

    public interface GameListener {
        void calibrateCompassIfNeeded()
    }
    
    public class Application extends ApplicationAdapter {
    
        private GameListener listener;    
    
        public Application(GameListener listener) {
            this.listener = listener;
        }
    
        @Override
        public void create() {
            // Call listener.calibrateCompassIfNeeded() whenever needed.
        }
    
        public void onCompassChanged(float[] values) {
            // Do something...
        }
    }
    

    android 模块中:

    public class AndroidLauncher extends AndroidApplication implements GameListener, SensorEventListener {
        private static final int COMPASS_ACCURACY_UNKNOWN = -1;
    
        private Application app;
        private int compassAccuracy = COMPASS_ACCURACY_UNKNOWN;
    
        @Override
        public void onCreate(Bundle state) {
            super.onCreate(state);
    
            SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
            Sensor compassSensor = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
            sensorManager.registerListener(this, compassSensor, SensorManager.SENSOR_DELAY_GAME)
    
            AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
            app = new Application(this);
            initialize(app, config);
        }
    
        @Override
        public void calibrateCompassIfNeeded() {
            if (compassAccuracy != COMPASS_ACCURACY_UNKNOWN && compassAccuracy < SENSOR_STATUS_ACCURACY_MEDIUM) {
                // Calibrate only if accuracy is below medium.
                // Show whatever is needed so user calibrates the compass.
            }
        }
    
        @Override
        public void onSensorChanged(SensorEvent event) {
            if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
                app.onCompassChanged(event.values);
            }
        }
    
        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {
           compassAccuracy = accuracy;
        }
    }
    

    我没有尝试过,也从未使用过指南针,但我很确定这会很好。

    【讨论】:

    • 如果罗盘读数是“常见的并且对其他平台有意义”,那么也应该检查同一个罗盘是否校准良好。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-09
    • 1970-01-01
    • 2015-03-26
    • 1970-01-01
    • 2012-11-23
    • 2016-08-20
    • 2020-04-06
    相关资源
    最近更新 更多