Condividi tramite


Usare l'accelerometro

Informazioni su come usare l'accelerometro per rispondere al movimento dell'utente.

API Importanti

Prerequisiti

Dovresti avere familiarità con Extensible Application Markup Language (XAML), Microsoft Visual C# ed eventi.

Il dispositivo o l'emulatore in uso deve supportare un accelerometro.

Creare una semplice app di accelerometro

Un'app di gioco semplice si basa su un singolo sensore, l'accelerometro, come dispositivo di input. Queste app usano in genere solo uno o due assi per l'input; ma possono anche usare l'evento shake come un'altra origine di input.

Annotazioni

Per un'implementazione più completa, vedere l'esempio di accelerometro .

Disposizioni

  • Creare un nuovo progetto scegliendo un'app vuota (universale Windows) dai modelli di progetto Visual C# .

  • Aprire il file di MainPage.xaml.cs del progetto e sostituire il codice esistente con il codice seguente.

    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;

    // Required to support the core dispatcher and the accelerometer

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

    namespace App1
    {

        public sealed partial class MainPage : Page
        {
            // Sensor and dispatcher variables
            private Accelerometer _accelerometer;

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

            private async void ReadingChanged(object sender, AccelerometerReadingChangedEventArgs e)
            {
                await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    AccelerometerReading reading = e.Reading;
                    txtXAxis.Text = String.Format("{0,5:0.00}", reading.AccelerationX);
                    txtYAxis.Text = String.Format("{0,5:0.00}", reading.AccelerationY);
                    txtZAxis.Text = String.Format("{0,5:0.00}", reading.AccelerationZ);

                });
            }

            public MainPage()
            {
                this.InitializeComponent();
                _accelerometer = Accelerometer.GetDefault();

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

                    // Assign an event handler for the reading-changed event
                    _accelerometer.ReadingChanged += new TypedEventHandler<Accelerometer, AccelerometerReadingChangedEventArgs>(ReadingChanged);
                }
            }
        }
    }

Sarai necessario rinominare il namespace nel frammento precedente con il nome che hai dato al tuo progetto. Ad esempio, se avete creato un progetto chiamato AccelerometerCS, sostituireste namespace App1 con namespace AccelerometerCS.

  • Aprire il file MainPage.xaml e sostituire il contenuto originale con il codice XML seguente.
        <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="25" Margin="8,20,0,0" TextWrapping="Wrap" Text="X-axis:" VerticalAlignment="Top" Width="62" Foreground="#FFEDE6E6"/>
            <TextBlock HorizontalAlignment="Left" Height="27" Margin="8,49,0,0" TextWrapping="Wrap" Text="Y-axis:" VerticalAlignment="Top" Width="62" Foreground="#FFF5F2F2"/>
            <TextBlock HorizontalAlignment="Left" Height="23" Margin="8,80,0,0" TextWrapping="Wrap" Text="Z-axis:" VerticalAlignment="Top" Width="62" Foreground="#FFF6F0F0"/>
            <TextBlock x:Name="txtXAxis" HorizontalAlignment="Left" Height="15" Margin="70,16,0,0" TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top" Width="61" Foreground="#FFF2F2F2"/>
            <TextBlock x:Name="txtYAxis" HorizontalAlignment="Left" Height="15" Margin="70,49,0,0" TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top" Width="53" Foreground="#FFF2EEEE"/>
            <TextBlock x:Name="txtZAxis" HorizontalAlignment="Left" Height="15" Margin="70,80,0,0" TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top" Width="53" Foreground="#FFFFF8F8"/>

        </Grid>
    </Page>

Dovrai sostituire la prima parte del nome della classe nel frammento di codice precedente con il namespace della tua app. Ad esempio, se avete creato un progetto chiamato AccelerometerCS, sostituireste x:Class="App1.MainPage" con x:Class="AccelerometerCS.MainPage". È anche consigliabile sostituire xmlns:local="using:App1" con xmlns:local="using:AccelerometerCS".

  • Premere F5 o selezionare Debug>Avvia debug per compilare, distribuire ed eseguire l'app.

Una volta eseguita l'app, è possibile modificare i valori dell'accelerometro spostando il dispositivo o usando gli strumenti dell'emulatore.

  • Arrestare l'app ritornando a Visual Studio e premendo MAIUSC+F5, oppure selezionare Debug>Interrompi debug per arrestare l'app.

Spiegazione

L'esempio precedente illustra quanto poco codice dovrai scrivere per integrare l'input dell'accelerometro nella tua app.

L'app stabilisce una connessione con l'accelerometro predefinito nel metodo MainPage.

_accelerometer = Accelerometer.GetDefault();

L'app definisce l'intervallo del report all'interno del metodo MainPage. Questo codice recupera l'intervallo minimo supportato dal dispositivo e lo confronta con un intervallo richiesto di 16 millisecondi (che approssima una frequenza di aggiornamento a 60 Hz). Se l'intervallo minimo supportato è maggiore dell'intervallo richiesto, il codice imposta il valore sul valore minimo. Altrimenti, imposta il valore al intervallo richiesto.

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

I nuovi dati dell'accelerometro vengono acquisiti nel metodo ReadingChanged. Ogni volta che il driver del sensore riceve nuovi dati dal sensore, passa i valori all'app usando questo gestore eventi. L'app registra questo gestore eventi nella riga seguente.

_accelerometer.ReadingChanged += new TypedEventHandler<Accelerometer,
AccelerometerReadingChangedEventArgs>(ReadingChanged);

Questi nuovi valori vengono scritti nei TextBlock trovati nel codice XAML del progetto.

<TextBlock x:Name="txtXAxis" HorizontalAlignment="Left" Height="15" Margin="70,16,0,0" TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top" Width="61" Foreground="#FFF2F2F2"/>
 <TextBlock x:Name="txtYAxis" HorizontalAlignment="Left" Height="15" Margin="70,49,0,0" TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top" Width="53" Foreground="#FFF2EEEE"/>
 <TextBlock x:Name="txtZAxis" HorizontalAlignment="Left" Height="15" Margin="70,80,0,0" TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top" Width="53" Foreground="#FFFFF8F8"/>