I am currently playing a bit around developing some android apps. I tried to implement a real simple game. I think everybody knows that kind of game. Your Device is a board and there is a ball on top of this board. If you move your device the ball will move.
I hope you got what I mean

Well its working fine, but only if I have my device flat on the ground. If I lift it up and hold it in front of me, the ball rolls "down". Thats what its supposed to do.
But it would be cool if I could implement it that I can calibrate the device (while holding it in front of me) and then just move the device to control the ball. Currently you can only "play" this game while holding the device it flat on the ground. I want to be able to play it in all positions.
So here is my code so far:
Can someone give me a hint how I can realize this? Thanks in advance!
Using java Syntax Highlighting
- public class SensorTestActivity extends Activity implements SensorEventListener{
- private SensorManager mSensorManager;
- private Point point = new Point(0,0);
- View v;
- TextView accView;
- TextView orientView;
- private boolean calibrated = false;
- /** Called when the activity is first created. */
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- LinearLayout layout = new LinearLayout(this);
- layout.setOrientation(LinearLayout.VERTICAL);
- accView = new TextView(this);
- layout.addView(accView);
- orientView = new TextView(this);
- layout.addView(orientView);
- v = new View(this){
- @Override
- protected void onDraw(Canvas canvas) {
- // TODO Auto-generated method stub
- super.onDraw(canvas);
- if (point.x == 0){
- point = new Point(canvas.getWidth()/2,canvas.getHeight()/2);
- }
- Paint p = new Paint();
- p.setColor(Color.RED);
- p.setStyle(Style.FILL_AND_STROKE);
- canvas.drawCircle(point.x, point.y, 20, p);
- }
- };
- layout.addView(v);
- setContentView(layout);
- mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
- boolean b = mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
- SensorManager.SENSOR_DELAY_GAME);
- Log.d("TEST","listener geadded: " + b);
- }
- @Override
- protected void onResume()
- {
- super.onResume();
- mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
- SensorManager.SENSOR_DELAY_GAME);
- }
- @Override
- protected void onStop()
- {
- // Unregister the listener
- mSensorManager.unregisterListener(this);
- super.onStop();
- }
- @Override
- public void onAccuracyChanged(Sensor sensor, int accuracy) {
- Log.d("TEST","changed");
- }
- float xoffset, yoffset ,zoffset;
- @Override
- public void onSensorChanged(SensorEvent event) {
- if (v != null){
- float x = event.values[0];
- float y = event.values[1];
- float z = event.values[2];
- point.x-=x;
- point.y+=y;
- Log.d("VALUES", "x: " + x + " y:" + y + " z: " +z);
- v.invalidate();
- }
- }
- }
Parsed in 0.041 seconds, using GeSHi 1.0.8.4


