Android Accelerometer Difficulties

I am starting to develop Android games, and I am developing a small game. I encounter some difficulties with a motion sensor: an accelerometer.

This game is in landscape mode. I want my phone to lean to the right, my character also did the right thing. (same for left) And when I stop the character’s tilt, the game should stop moving.

But I don’t understand the operation of the accelerometer very well,

here is my code:

@Override public void onSensorChanged(SensorEvent event) { synchronized (this) { long penchement = (long) (event.values[1]- 0.5); if(penchement>0){ if(penchement>lastUpdate) lastUpdate=penchement; if(penchement>0.2){ booldroite=true; // boolean for going right boolgauche=false; // boolean for going left } if(lastUpdate-penchement<0.2) booldroite=false; } else{ if(penchement<lastUpdate) lastUpdate=penchement; if(penchement<-0.2){ boolgauche=true; booldroite=false; } if(lastUpdate+penchement>-0.2) boolgauche=false; } } 

So, my code works (a bit), but my character movements are not smooth. Sometimes my phone tilts, but my characters do not move ...

Thank you in advance if you can help me.

+1
android accelerometer sensor andengine
Dec 18 '12 at 15:04
source share
1 answer

The readings of the sensors sound by nature, which is the reason for the flickering movement of your character.

After reading, you will need to implement some sort of low pass filter. Here is an example of a basic low-pass filter in SensorEvent .

  public void onSensorChanged(SensorEvent event) { // alpha is calculated as t / (t + dT) // with t, the low-pass filter time-constant // and dT, the event delivery rate final float alpha = 0.8; gravity[0] = alpha * gravity[0] + (1 - alpha) * event.values[0]; gravity[1] = alpha * gravity[1] + (1 - alpha) * event.values[1]; gravity[2] = alpha * gravity[2] + (1 - alpha) * event.values[2]; linear_acceleration[0] = event.values[0] - gravity[0]; linear_acceleration[1] = event.values[1] - gravity[1]; linear_acceleration[2] = event.values[2] - gravity[2]; } 

You can use the values ​​in gravity[] to find out the tilt of the phone. Also, play around with a final float alpha value: values ​​around 1.0 will improve smoothness, while lower values ​​around 0.0 will get a louder reading, but have a faster response.

Bonn's chance!

+2
Dec 18 '12 at 15:25
source share



All Articles