在Windows Phone 7上检测震动(译文)
By S.F.
本文链接 https://www.kyfws.com/news/detect-shaking-motion-on-windows-phone/
版权声明 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
- 3 分钟阅读 - 1085 个词 阅读量 0在Windows Phone 7上检测震动(译文)
原文地址:https://www.codeproject.com/Articles/98492/Detect-Shaking-Motion-on-Windows-Phone
原文作者:Joel Ivory Johnson
译文由本站翻译
前言
在Windows Phone 7上检测震动的一种方法的演示
下载代码 前几天在MSDN论坛上,有人问到如何在Windows Phone 7上检测到震动.我最近一直在使用加速度计,因此我很高兴在回答这一问题的同时提供了可行的实现.问题是询问左右方向的晃动.我制作了一个类,它检测左右运动(暂时完全忽略Z轴).尽管将其扩展为考虑Z轴并不难. 用于检测运动的代码已在称为" ShakeDetector"的类中抽象.使用的算法定义了一些变量/常量,可以对其进行修改以调整类的行为.类构造函数接受一个[可选]参数,该参数应将手机摇动多少次才能认为该动作可以接受.可以升高或降低" ",以控制需要摇晃多久才能使设备被接受.而" MinimumShakeTime"采用一个时间跨度,该时间跨度定义了必须发生摇动序列才能被视为可接受的最大时间长度.一旦用户以符合震动类型要求的方式移动手机,我们便希望检测到" ShakeDetected"事件被触发. 我已将设备移动的方向减小到8个方向之一(“北”,“东”,“南”,“西"以及这两个方向之间的方向).我本可以将方向保持为一个角度,只是确保角度之间的差异最小,但是我认为在地图上使用这些方向将使其他人更容易理解.
void _accelerometer_ReadingChanged(object sender, AccelerometerReadingEventArgs e)
{
//Does the current acceleration vector meet the minimum magnitude that we
//care about?
if ((e.X*e.X + e.Y*e.Y) > MinimumAccelerationMagnitudeSquared)
{
//I prefer to work in radians. For the sake of those reading this code
//I will work in degrees. In the following direction will contain the direction
// in which the device was accelerating in degrees.
double degrees = 180.0*Math.Atan2(e.Y, e.X)/Math.PI;
Direction direction = DegreesToDirection(degrees);
//If the shake detected is in the same direction as the last one then ignore it
if ((direction & _shakeRecordList[_shakeRecordIndex].ShakeDirection)
!= Direction.None)
return;
//This is a shake we care about. save in our list
ShakeRecord record = new ShakeRecord();
record.EventTime = DateTime.Now;
record.ShakeDirection = direction;
_shakeRecordIndex = (_shakeRecordIndex + 1)%_minimumShakes;
_shakeRecordList[_shakeRecordIndex] = record;
CheckForShakes();
}
}
void CheckForShakes()
{
int startIndex = (_shakeRecordIndex - 1);
if (startIndex < 0) startIndex = _minimumShakes - 1;
int endIndex = _shakeRecordIndex;
if ((_shakeRecordList[endIndex].EventTime.Subtract
(_shakeRecordList[startIndex].EventTime)) <= MinimumShakeTime)
{
OnShakeEvent();
}
}
可以在我的SkyDrive帐户此处中找到示例代码.如果您想查看正在运行的程序,请在[YouTube]上观看视频[http://cid-2a0d66a555ad369a.office.live.com/self.aspx/code/ShakeTest.zip)(http://www.youtube.com/watch?v=vLhCyp9il9o). CodeProject
许可
本文以及所有相关的源代码和文件均已获得The Code Project Open License (CPOL)的许可。
Windows-Phone-7 新闻 翻译