Search code examples
javaandroidaccelerometershake

Android Shake Code


In my game I want the player to shake his phone, at any point during the game, and every shake will result in switching weapons.

Example: Player has knife, [shakes phone] and switches to a katana.

if (accelerometer.x >= 5 || accelerometer.x <= -5   || accelerometer.y >= 5 
   || accelerometer.y <= -5   || accelerometer.z >= 5 || accelerometer.z <= -5 )
   switchWep();        

This works, the problem is it has a side effect.When the player shakes the phone sometimes it switches weapons twice. So I want to limit it so that if there is a big shake the game doesn't switch from weapon 0 to weapon 2.

Please help.


Solution

  • You could put a simple time limitation on so you can't switch 2 times after each other. I think 1 sec - 500 msec would be sufficient to avoid a double switch.

    Edit: You could do this, but I'm not sure its the most optimal or lock safe way to do it.

    protected void shake() {
        if(mAllowShake) {
            mAllowShake = false;
    
            // do shake
    
            Handler handler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    mAllowShake = true;
                }
            };
    
            handler.sendMessageDelayed(null, 500);  // time in milliseconds
        }
    }