UWP開發中的方向傳感器

  在UWP開發中,咱們能使用的到方向有三種: OrientationSensor下的四元數;Compass羅盤的HeadingMagneticNorth;以及SimpleOrientationSensor。google

  先說下SimpleOrientationSensor,這個是用在比較簡單的狀況下,它只能讀取6個方向:旋轉0,90,180,270,FaceUP,FaceDown。spa

        var simpleOrien = SimpleOrientationSensor.GetDefault().GetCurrentOrientation();
            switch (simpleOrien)
            {
                case SimpleOrientation.Facedown:
                    // To do ...
                    break;
                case SimpleOrientation.Faceup:
                    // To do ...
                    break;
                case SimpleOrientation.NotRotated:
                    // To do ...
                    break;
                case SimpleOrientation.Rotated180DegreesCounterclockwise:
                    // To do ...
                    break;
                case SimpleOrientation.Rotated270DegreesCounterclockwise:
                    // To do ...
                    break;
                case SimpleOrientation.Rotated90DegreesCounterclockwise:
                    // To do ...
                    break;
            }

羅盤:code

        var compass = Compass.GetDefault().GetCurrentReading();
            var angle= compass.HeadingMagneticNorth;

使用很簡單,可是它讀取的彷佛是你行進的方向,也就是說假如你站着不動的話,讀數是沒有意義的。htm

方向傳感器:blog

        var _sensor = OrientationSensor.GetDefault();
            var quaternion = _sensor.GetCurrentReading().Quaternion;
            var heading = 180 * Math.Atan2(2 * (quaternion.W * quaternion.Z + quaternion.X * quaternion.Y), 1 - 2 * (quaternion.Y * quaternion.Y + quaternion.Z * quaternion.Z)) / Math.PI;

這個可能要稍微麻煩一點,由於它涉及到四元數,有關四元數的知識請自行google或翻書開發

相關文章
相關標籤/搜索