Java Android,基于地磁传感器调用GLROTAEF
我有一个渲染立方体的应用程序。我对使用openGL制作3d有点陌生,但本质上我想要的是立方体的一个角始终指向北方,同时根据地磁传感器确定自身的方向 这样,当用户将手机与地面平行并朝北时,手机的角将指向屏幕上的上方,而如果用户将手机直立,则手机的角将指向远离用户的方向,朝向手机的背面 我在2d中只在一个旋转轴上写下这个,这样当手机与地面平行时,它就会指向北边的角落 然而,当我制作这个3D时,其中两个轴似乎工作正常,但我第一次使用的轴的行为似乎不一样 我使用以下代码来获取每种类型的旋转:Java Android,基于地磁传感器调用GLROTAEF,java,android,opengl-es,3d,Java,Android,Opengl Es,3d,我有一个渲染立方体的应用程序。我对使用openGL制作3d有点陌生,但本质上我想要的是立方体的一个角始终指向北方,同时根据地磁传感器确定自身的方向 这样,当用户将手机与地面平行并朝北时,手机的角将指向屏幕上的上方,而如果用户将手机直立,则手机的角将指向远离用户的方向,朝向手机的背面 我在2d中只在一个旋转轴上写下这个,这样当手机与地面平行时,它就会指向北边的角落 然而,当我制作这个3D时,其中两个轴似乎工作正常,但我第一次使用的轴的行为似乎不一样 我使用以下代码来获取每种类型的旋转: g
gl.glPushMatrix();
gl.glTranslatef(0,0,-4);
//get target angle
targetAngle1 = rotationHandler.getRotation1();
targetAngle2 = rotationHandler.getRotation2();
targetAngle3 = rotationHandler.
if (Math.abs(getShortestAngle(targetAngle1, currentAngle)) > 5) //this is to create a 5 degree "dead zone" so the compass isnt shaky
currentAngle1 = (getShortestAngle(currentAngle, targetAngle1) > 0) ?
currentAngle+1f : currentAngle-1f; //increase or decrease the current angle to move it towards the target angle
if (Math.abs(getShortestAngle(targetAngle2, currentAngle2))>5)
currentAngle2 = (getShortestAngle(currentAngle2, targetAngle2) > 0) ?
currentAngle2 + 1f : currentAngle2-1f;
if (Math.abs(getShortestAngle(targetAngle3, currentAngle3))>5)
currentAngle3 = (getShortestAngle(currentAngle3, targetAngle3) > 0) ?
currentAngle3 + 1f : currentAngle3 - 1f;
gl.glRotatef(currentAngle, 0, 0, -4);
gl.glRotatef(currentAngle2, 0, -4, 0);
gl.glRotatef(currentAngle3, -4, 0, 0);
cube.draw(gl);
gl.glPopMatrix();
使用currentAngle2和currentAngle3调用glRotatef时,似乎会在相对于立方体的轴上旋转立方体,而第一个调用似乎会在相对于屏幕的轴上旋转立方体。当我注释掉任何两个旋转调用时,第三个按预期工作。但我似乎不知道如何让他们一起工作
--编辑--
我发现我可以让立方体旋转到几乎任何可能的位置,即使在取消第一次调用之后。看来我得想出一个算法来计算旋转。老实说,我不知道我是否能做到这一点,但如果我找到答案,我会把它贴在这里。这可能不是最好的解决方案,但只要手机不是完全平坦的,它似乎就可以工作 将模型更改为矩形棱镜后,我可以更清楚地处理这个问题。我只使用了前两个轴,甚至没有接触最后一个轴。我把棱柱体当作战斗机一样对待——为了向左或向右转动,我将其侧向旋转,然后上下改变俯仰。然后我取消旋转它,再次改变音高,使其适当地指向上或下
public void findTargetRotation(float rotationAngle, float pitchAngle, GL10 gl){
//first, enable rotation around a vertical axis by rotating on frontBack axis by -90 degrees
gl.glRotatef(-90, 0, -4, 0);
//rotate around the leftRight axis by the angle1 amount
gl.glRotatef(rotationAngle, 0,-4,0);
//then rotate on frontBack axis by 90 degrees again, to straighten out
gl.glRotatef(90, 0, -4, 0);
//lastly, rotate around the leftRight axis to point it up or down
gl.glRotatef(pitchAngle, -4, 0, 0);
}
只要俯仰角不是非常接近或等于0,这似乎是可行的。如果俯仰角真的很小的话,我只是添加了一些代码,把它当作一个2D对象
也许有更好的解决方案,但至少这是可行的