Similar to the native part, you can use other sensors in the managed part as well, including the gyroscope and compass. A process of using the first one is described shortly in this part, while the compass example is shown in Chapter 10, Social Networks, Feeds, Settings, and Local Rank.
To read data from the gyroscope you need to make some modifications in the view model. You start with creating a field representing a gyroscope:
private Gyroscope m_gyroscope;
An initialization of the gyroscope is very similar to the accelerometer setup. You check whether the gyroscope sensor is supported and then create a new instance of the Gyroscope
class, handle the CurrentValueChanged
event, and start using the gyroscope. In case of any exception, you just set the value of m_gyroscope
to null
. The process of initialization is presented in the following code:
public void OnNavigatedTo(NavigationEventArgs e) { (...) if (Gyroscope.IsSupported) { try { this.m_gyroscope = new Gyroscope(); this.m_gyroscope.CurrentValueChanged += this.Gyroscope_CurrentValueChanged; this.m_gyroscope.Start(); } catch (Exception) { this.m_gyroscope = null; } } }
The Gyroscope_CurrentValueChanged
method just writes a line with obtained data to the output, thus you can analyze them in the Output window. It is worth mentioning that you can access angular velocity along x, y, and z axis by the RotationRate
property (of the GyroscopeReading
instance) and its X
, Y
, and Z
properties, as shown in the following code snippet:
private void Gyroscope_CurrentValueChanged(object sender, SensorReadingEventArgs<GyroscopeReading> e) { Debug.WriteLine("Gyroscope data: {0} (x in rad/s), {1} (y in rad/s), {2} (z in rad/s)", e.SensorReading.RotationRate.X, e.SensorReading.RotationRate.Y, e.SensorReading.RotationRate.Z); }
To write values to the output, the WriteLine
static method from the Debug
class is used. This class is located in the System.Diagnostics
namespace.
Similar to the accelerometer usage, you should ensure that the gyroscope is stopped as soon as it is no longer used by your application:
public void OnNavigatedFrom(NavigationEventArgs e) { (...) if (this.m_gyroscope != null) { this.m_gyroscope.Stop(); this.m_gyroscope = null; } }
After launching the game on the phone equipped with the gyroscope sensor and connected to the PC, you should see data obtained from this sensor in the Output window.
18.221.136.142