Search code examples
javaandroidmobileaccelerometer

android Accelerometer on X-Axis


I think this is a simple question for you guys (it's just I'm new in this business):
so, In my android java-based game I have this ball, and..
I want to detect the user movement.
if the user tilt the device to the right, the ball will roll to the right side
if the user tilt the device to the left, the ball will roll to the left side.

so, in short:
how to "connect" the ball to the device-movement (only on x-axis - right & left)

thanks,
sock.socket


Solution

  • First, declare your Sensor and sensor manager

    public Sensor mySensor;
    private SensorManager mySensorManager;
    

    Then initialize the variables to your liking. I chose to have my sensor delay as normal and my accuracy sensitivity to high.

    mySensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
    mySensor = mySensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
    mySensorManager.registerListener(this, mySensor, SensorManager.SENSOR_DELAY_NORMAL, SensorManager.SENSOR_STATUS_ACCURACY_HIGH);
    

    Now you will need an onSensorChanged function that will run every time your sensor senses a change. Within this function, you can animate your ball.

    @Override
    public void onSensorChanged(SensorEvent event) {
        x = event.values[0];
    
        // The x value in the accelerometer is the 0th index in the array
    
        // Now you may do what you wish with this x value, and use it to move your ball 
        }
    }