×
Namespaces

Variants
Actions

Talk:Using the Accelerometer in windows phone for shake app interaction

From Nokia Developer Wiki
Jump to: navigation, search

PetruMotrescu - Unnecessary complexity

All those transformations from Vector3 and float[] I believe are not needed. Also, Vector3 already has a Length function, that does the same thing your Magnitude() does. Better yet, no need for sqrt if you need the delta of change (you just set the threshold higher), hence we are better off using LengthSquared(). Have a look at this more straightforward solution:

using Microsoft.Devices.Sensors;
using Microsoft.Xna.Framework;
using System;

namespace Test
{
    public interface IShakeDetector
    {
        event EventHandler Shaked;
        void Start();
        void Stop();
        void Dispose();
    }

    public class ShakeDetector : IShakeDetector
    {
        private static readonly float THRESHOLD = 0.1f;
        private Accelerometer accelerometer;
        private Vector3? acceleration;

        public event EventHandler Shaked;

        public ShakeDetector()
        {
            if (Accelerometer.IsSupported)
            {
                this.accelerometer = new Microsoft.Devices.Sensors.Accelerometer();
            }
        }

        public void Start()
        {
            if (this.accelerometer != null)
            {
                this.acceleration = null;
                this.accelerometer.CurrentValueChanged += Accelerometer_CurrentValueChanged;
                this.accelerometer.Start();
            }
        }

        public void Stop()
        {
            if (this.accelerometer != null)
            {
                this.accelerometer.CurrentValueChanged -= Accelerometer_CurrentValueChanged;
                this.accelerometer.Stop();
            }
        }

        public void Dispose()
        {
            if (this.accelerometer != null)
            {
                this.accelerometer.Dispose();
                this.accelerometer = null;
            }
        }

        private void Accelerometer_CurrentValueChanged(Object con, SensorReadingEventArgs<AccelerometerReading> e)
        {
            if (Shaked != null)
            {
                Vector3 newAcceleration = e.SensorReading.Acceleration;

                if (this.acceleration != null)
                {
                    if (Math.Abs(this.acceleration.Value.LengthSquared() - newAcceleration.LengthSquared()) > THRESHOLD)
                    {
                        Shaked(this, EventArgs.Empty);
                    }
                }

                this.acceleration = newAcceleration;
            }
        }
    }
}

PetruMotrescu (talk) 10:34, 4 December 2013 (EET)

 

Was this page helpful?

Your feedback about this content is important. Let us know what you think.

 

Thank you!

We appreciate your feedback.

×