安卓游戏My Paper Plane是一个很好的例子,说明了如何实现倾斜控制,但我一直在努力理解如何才能做类似的事情。
下面的示例使用了SensorManager中的getOrientation()。整件事都在pastebin here上。它只是将方向值打印到文本字段。下面是最相关的代码片段:
private void computeOrientation() {
if (SensorManager.getRotationMatrix(m_rotationMatrix, null,
m_lastMagFields, m_lastAccels)) {
SensorManager.getOrientation(m_rotationMatrix, m_orientation);
/* 1 radian = 57.2957795 degrees */
/* [0] : yaw, rotation around z axis
* [1] : pitch, rotation around x axis
* [2] : roll, rotation around y axis */
float yaw = m_orientation[0] * 57.2957795f;
float pitch = m_orientation[1] * 57.2957795f;
float roll = m_orientation[2] * 57.2957795f;
/* append returns an average of the last 10 values */
m_lastYaw = m_filters[0].append(yaw);
m_lastPitch = m_filters[1].append(pitch);
m_lastRoll = m_filters[2].append(roll);
TextView rt = (TextView) findViewById(R.id.roll);
TextView pt = (TextView) findViewById(R.id.pitch);
TextView yt = (TextView) findViewById(R.id.yaw);
yt.setText("azi z: " + m_lastYaw);
pt.setText("pitch x: " + m_lastPitch);
rt.setText("roll y: " + m_lastRoll);
}
}问题是,它输出的值看起来像是无稽之谈,或者至少没有办法区分用户执行的是哪种类型的动作。我已经画了一个图表来指出我想要检测的两种运动类型- 1.“倾斜”表示俯仰,2.“旋转”表示滚动/转向:

(当然,这是横向模式下手机的等距视图)
当我沿着手机的长轴向前和向后倾斜时-显示为1。-我预计只有1个值会有很大变化,但所有这些值似乎都有很大的变化。类似地,如果我将手机绕着屏幕上出现的一条假想线旋转-如图2所示-我希望只有滚动值改变,但所有的值都改变了很多。
问题是,当我校准我的游戏时-这意味着记录x,y和z的当前值-我后来不知道如何解释传入的更新角度来说“好吧,看起来你已经倾斜了手机,你想向左滚动3度”。它更像是“好吧,你已经移动了手机,你同时在a-tiltin‘和a-rollin’”,即使意图只是一个滚动。讲得通?
有什么想法吗?我已经尝试使用remapCoordinateSystem来查看更改轴是否有任何效果。不是,是joy。我想我遗漏了一些基本的东西:
发布于 2011-01-02 09:54:13
你把加速器和磁传感器阵列混在一起了。代码应该是:
if (SensorManager.getRotationMatrix(m_rotationMatrix, null,
m_lastAccels, m_lastMagFields)) {查看getRotationMatrix(..)
https://stackoverflow.com/questions/4576493
复制相似问题