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

查看:18
本文介绍了如何在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?

这些游戏做了类似的事情:极限滑冰者,涂鸦跳跃.

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

PS:我的手机方向是横向.

PS: my phone orientation will be landscape.

推荐答案

本质上,这里有两种情况:设备平放和不平放.这里的平面是指设备屏幕表面与世界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.

首先,您需要对加速度计矢量进行归一化.
也就是说,如果 g 是加速度计传感器事件值返回的向量.在代码中

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

那么倾角可以计算为

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天全站免登陆