다음을 통해 공유


경사계 사용하기

경사계를 사용하여 pitch, roll 및 yaw를 결정하는 방법을 알아봅니다.

중요 API

필수 조건

XAML(Extensible Application Markup Language), Microsoft Visual C#, 이벤트에 대해 잘 알고 있어야 합니다.

사용 중인 디바이스 또는 에뮬레이터는 경사계를 지원해야 합니다.

간단한 경사계 앱 만들기

일부 3D 게임에는 입력 장치로서 경사계가 필요합니다. 한 가지 일반적인 예는 경사계의 세 축(X, Y 및 Z)을 항공기의 엘리베이터, 에일런 및 방향타 입력에 매핑하는 비행 시뮬레이터입니다.

참고

더 완전한 구현은 경사계 샘플을 참조하세요.

지침

  • Visual C# 프로젝트 템플릿에서 빈 앱(Universal Windows)을 선택하여 새 프로젝트를 만듭니다.

  • 프로젝트의 MainPage.xaml.cs 파일을 열고 기존의 코드를 다음과 같이 바꿉니다.

    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using Windows.Foundation;
    using Windows.Foundation.Collections;
    using Windows.UI.Xaml;
    using Windows.UI.Xaml.Controls;
    using Windows.UI.Xaml.Controls.Primitives;
    using Windows.UI.Xaml.Data;
    using Windows.UI.Xaml.Input;
    using Windows.UI.Xaml.Media;
    using Windows.UI.Xaml.Navigation;

    using Windows.UI.Core;
    using Windows.Devices.Sensors;


    namespace App1
    {
        /// <summary>
        /// An empty page that can be used on its own or navigated to within a Frame.
        /// </summary>
        public sealed partial class MainPage : Page
        {
            private Inclinometer _inclinometer;

            // This event handler writes the current inclinometer reading to
            // the three text blocks on the app' s main page.

            private async void ReadingChanged(object sender, InclinometerReadingChangedEventArgs e)
            {
                await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    InclinometerReading reading = e.Reading;
                    txtPitch.Text = String.Format("{0,5:0.00}", reading.PitchDegrees);
                    txtRoll.Text = String.Format("{0,5:0.00}", reading.RollDegrees);
                    txtYaw.Text = String.Format("{0,5:0.00}", reading.YawDegrees);
                });
            }

            public MainPage()
            {
                this.InitializeComponent();
                _inclinometer = Inclinometer.GetDefault();


                if (_inclinometer != null)
                {
                    // Establish the report interval for all scenarios
                    uint minReportInterval = _inclinometer.MinimumReportInterval;
                    uint reportInterval = minReportInterval > 16 ? minReportInterval : 16;
                    _inclinometer.ReportInterval = reportInterval;

                    // Establish the event handler
                    _inclinometer.ReadingChanged += new TypedEventHandler<Inclinometer, InclinometerReadingChangedEventArgs>(ReadingChanged);
                }
            }
        }
    }

이전 코드 조각의 네임스페이스의 이름을 프로젝트에 지정한 이름으로 바꿔야 합니다. 예를 들어 InclinometerCS라는 프로젝트를 만든 경우, namespace App1을(를) namespace InclinometerCS(으)로 교체합니다.

  • MainPage.xaml 파일을 열고 이 파일의 원본 내용을 다음의 XAML로 바꿉니다.
        <Page
        x:Class="App1.MainPage"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="using:App1"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d">

        <Grid x:Name="LayoutRoot" Background="#FF0C0C0C">
            <TextBlock HorizontalAlignment="Left" Height="21" Margin="0,8,0,0" TextWrapping="Wrap" Text="Pitch: " VerticalAlignment="Top" Width="45" Foreground="#FFF9F4F4"/>
            <TextBlock x:Name="txtPitch" HorizontalAlignment="Left" Height="21" Margin="59,8,0,0" TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top" Width="71" Foreground="#FFFDF9F9"/>
            <TextBlock HorizontalAlignment="Left" Height="23" Margin="0,29,0,0" TextWrapping="Wrap" Text="Roll:" VerticalAlignment="Top" Width="55" Foreground="#FFF7F1F1"/>
            <TextBlock x:Name="txtRoll" HorizontalAlignment="Left" Height="23" Margin="59,29,0,0" TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top" Width="50" Foreground="#FFFCF9F9"/>
            <TextBlock HorizontalAlignment="Left" Height="19" Margin="0,56,0,0" TextWrapping="Wrap" Text="Yaw:" VerticalAlignment="Top" Width="55" Foreground="#FFF7F3F3"/>
            <TextBlock x:Name="txtYaw" HorizontalAlignment="Left" Height="19" Margin="55,56,0,0" TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top" Width="54" Foreground="#FFF6F2F2"/>

        </Grid>
    </Page>

이전 코드 조각에서 클래스 이름의 첫 번째 부분을 앱의 네임스페이스로 바꿔야 합니다. 예를 들어 InclinometerCS라는 프로젝트를 만든 경우, x:Class="App1.MainPage"을(를) x:Class="InclinometerCS.MainPage"(으)로 교체합니다. 또한 xmlns:local="using:App1"을(를) xmlns:local="using:InclinometerCS"(으)로 대체해야 합니다.

  • F5 키를 누르거나 디버그>디버깅 시작을 선택하여 앱을 빌드하고 배포하고 실행합니다.

앱이 실행되면 경사계 값을 변경하기 위해 디바이스를 이동하거나 Emulator 도구를 사용할 수 있습니다.

  • Visual Studio로 돌아가서 Shift+F5를 눌러 앱을 중지하거나 디버그>디버깅 중지를 선택하여 앱을 중지합니다.

설명

이전 예시는 앱에서 경사계 입력을 통합하기 위해 작성해야 하는 코드가 얼마나 적은지를 보여 줍니다.

앱은 MainPage 메서드에서 기본 경사계와의 연결을 설정합니다.

_inclinometer = Inclinometer.GetDefault();

앱은 MainPage 메서드 내에서 보고서 간격을 설정합니다. 이 코드는 디바이스에서 지원하는 최소 간격을 검색하고 요청된 간격인 16밀리초(약 60Hz 새로 고침 속도)와 비교합니다. 지원되는 최소 간격이 요청된 간격보다 큰 경우 코드는 값을 최소값으로 설정합니다. 그렇지 않으면 값을 요청된 간격으로 설정합니다.

uint minReportInterval = _inclinometer.MinimumReportInterval;
uint reportInterval = minReportInterval > 16 ? minReportInterval : 16;
_inclinometer.ReportInterval = reportInterval;

새로운 경사계 데이터는 ReadingChanged 메서드에서 캡처됩니다. 센서 드라이버가 센서에서 새 데이터를 받을 때마다 이 이벤트 처리기를 사용하여 값을 앱에 전달합니다. 앱은 다음의 줄에 이 이벤트 처리기를 등록합니다.

_inclinometer.ReadingChanged += new TypedEventHandler<Inclinometer,
InclinometerReadingChangedEventArgs>(ReadingChanged);

이러한 새 값은 프로젝트의 XAML에 있는 TextBlocks에 기록됩니다.

<TextBlock HorizontalAlignment="Left" Height="21" Margin="0,8,0,0" TextWrapping="Wrap" Text="Pitch: " VerticalAlignment="Top" Width="45" Foreground="#FFF9F4F4"/>
 <TextBlock x:Name="txtPitch" HorizontalAlignment="Left" Height="21" Margin="59,8,0,0" TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top" Width="71" Foreground="#FFFDF9F9"/>
 <TextBlock HorizontalAlignment="Left" Height="23" Margin="0,29,0,0" TextWrapping="Wrap" Text="Roll:" VerticalAlignment="Top" Width="55" Foreground="#FFF7F1F1"/>
 <TextBlock x:Name="txtRoll" HorizontalAlignment="Left" Height="23" Margin="59,29,0,0" TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top" Width="50" Foreground="#FFFCF9F9"/>
 <TextBlock HorizontalAlignment="Left" Height="19" Margin="0,56,0,0" TextWrapping="Wrap" Text="Yaw:" VerticalAlignment="Top" Width="55" Foreground="#FFF7F3F3"/>
 <TextBlock x:Name="txtYaw" HorizontalAlignment="Left" Height="19" Margin="55,56,0,0" TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top" Width="54" Foreground="#FFF6F2F2"/>