Search code examples
androidopengl-esaccelerometer

Accelerometer for android game can't move in the right way


i'm making a game with accelerometer feature, so that each time i turn my device to the left, the ship will bank left, and vice versa the problem is that the ship keep moving left by itself here's my code

public void onSensorChanged(SensorEvent event){
    if(event.sensor.getType()==Sensor.TYPE_ACCELEROMETER){
        float x = event.values[0];

        deltaX = xBefore-x;
        xBefore = x;
        if(deltaX>0){//move right
            SFEngine.playerFlightAction = SFEngine.PLAYER_LEFT_BANK_1;
        }else{//move left
            SFEngine.playerFlightAction =SFEngine.PLAYER_RIGHT_BANK_1;
        }
    }
}

Solution

  • You should not use any delta. Just check if x > 0, then move it to the left, else to the right

    deltaX is not calculated well in your code. It does not consider that xBefore can be less than zero and current x is greater than zero (or other way round). Delta should be calculated using absolute value.

    However I suppose that you really don't need any delta here. Just use x.