I want to get the android sensors to work with opengl to rotate the opengl's camera to wherever the phone is pointing to.
To elaborate: if the player is looking at east, I'd like to the opengl's camera points east too on the game; if the player points to the sky, I'd like to point the opengl's camera to the sky and so on.
I've tried using getRotationMatrix
and load the matrix on the opengl but it only works on the up-down direction, if I turn the cell to the sides, there is no difference. Here is what I've done so far (the app is in landscape mode):
public void onSensorChanged(SensorEvent evt) {
int type=evt.sensor.getType();
float alpha = 0.8f;
//Smoothing the sensor data a bit
if (type == Sensor.TYPE_MAGNETIC_FIELD) {
geomag[0]=geomag[0]*alpha+evt.values[0]*(1-alpha);
geomag[1]=geomag[1]*alpha+evt.values[1]*(1-alpha);
geomag[2]=geomag[2]*alpha+evt.values[2]*(1-alpha);
} else if (type == Sensor.TYPE_ACCELEROMETER) {
gravity[0]= gravity[0]*alpha+evt.values[0]*(1-alpha);
gravity[1]= gravity[1]*alpha+evt.values[1]*(1-alpha);
gravity[2]= gravity[2]*alpha+evt.values[2]*(1-alpha);
}
if ((type==Sensor.TYPE_MAGNETIC_FIELD) || (type==Sensor.TYPE_ACCELEROMETER)) {
rotationMatrix = new float[16];
SensorManager.getRotationMatrix(rotationMatrix, null, gravity, geomag);
SensorManager.remapCoordinateSystem(
rotationMatrix,
SensorManager.AXIS_Y,
SensorManager.AXIS_MINUS_X,
rotationMatrix );
if (AOGLRenderer.rotationmatrix==null) AOGLRenderer.rotationmatrix = new float[16];
AOGLRenderer.rotationmatrix = rotationMatrix;
}
}
and in the opengl code:
gl.glClear(GL10.GL_COLOR_BUFFER_BIT | // OpenGL docs.
GL10.GL_DEPTH_BUFFER_BIT);
gl.glLoadIdentity();
if (rotationmatrix!=null) gl.glLoadMatrixf(rotationmatrix, 0);
gl.glPushMatrix();
gl.glTranslatef(0, 0, -70);
g.draw(gl);
gl.glPopMatrix();
alpha+=2f;
gl.glTranslatef(0, -15, 0);
c.draw(gl);
I'd like that someone who actually did it could share their code! I'd really appreciate it! Thank you all!