如何在Android中使用加速计来测量手机在XY平面倾斜 [英] How to measure the tilt of the phone in XY plane using accelerometer in Android

查看:162
本文介绍了如何在Android中使用加速计来测量手机在XY平面倾斜的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从SensorEvent.values​​使用Z轴的数据,但它不能检测我的电话的旋转在XY平面,即绕Z轴。

I tried to use the Z axis data from SensorEvent.values, but it doesn't detect rotation of my phone in the XY plane, ie. around the Z-axis.

我用这作为坐标轴的参考。它正确?

I am using this as a reference for the co-ordinate axes. Is it correct?

我如何衡量运动使用加速度计值?

How do I measure that motion using accelerometer values?

这些游戏做同样的事情:<一href="https://play.google.com/store/apps/details?id=com.miniclip.extremeskater&feature=search_result#?t=W251bGwsMSwxLDEsImNvbS5taW5pY2xpcC5leHRyZW1lc2thdGVyIl0.">Extreme滑板,涂鸦跳跃。

These games do something similar: Extreme Skater, Doodle Jump.

PS:我的手机定位将是景观

PS: my phone orientation will be landscape.

推荐答案

从本质上讲,有2箱子这里:该设备是铺设平整,不平整。平在这里是指在设备屏幕表面和世界xy平面(我把它叫做倾斜)之间的夹角小于25度或大于155度。想想在手机平放,或从表中倾斜了,只是一点点。

Essentially, there is 2 cases here: the device is laying flat and not flat. Flat here means the angle between the surface of the device screen and the world xy plane (I call it the inclination) is less than 25 degree or larger than 155 degree. Think of the phone lying flat or tilt up just a little bit from a table.

首先,你需要规范化加速度矢量。
也就是说,如果是矢量收益率的加速度计传感器事件的值。在code

First you need to normalize the accelerometer vector.
That is if g is the vector returns by the accelerometer sensor event values. In code

float[] g = new float[3]; 
g = event.values.clone();

double norm_Of_g = Math.sqrt(g[0] * g[0] + g[1] * g[1] + g[2] * g[2]);

// Normalize the accelerometer vector
g[0] = g[0] / norm_Of_g
g[1] = g[1] / norm_Of_g
g[2] = g[2] / norm_Of_g

然后,倾斜可以被计算为

Then the inclination can be calculated as

int inclination = (int) Math.round(Math.toDegrees(Math.acos(g[2])));

于是

if (inclination < 25 || inclination > 155)
{
    // device is flat
}
else
{
    // device is not flat
}

有关放平的情况下,你必须使用一个指南针,看看有多少设备是从起始位置转动。

For the case of laying flat, you have to use a compass to see how much the device is rotating from the starting position.

有关的情况并非如此平,旋转(倾斜)被计算如下

For the case of not flat, the rotation (tilt) is calculated as follow

int rotation = (int) Math.round(Math.toDegrees(Math.atan2(g[0], g[1])));

现在旋转= 0表示该装置处于正常位置。这就是肖像没有任何倾斜于大多数手机和景观可能为平板电脑。所以,如果你持有的手机在你上面的图片,并开始旋转,旋转会改变,当手机在横向旋转将是90或-90取决于旋转方向。

Now rotation = 0 means the device is in normal position. That is portrait without any tilt for most phone and probably landscape for tablet. So if you hold a phone as in your picture above and start rotating, the rotation will change and when the phone is in landscape the rotation will be 90 or -90 depends on the direction of rotation.

这篇关于如何在Android中使用加速计来测量手机在XY平面倾斜的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆