Pregunta

I am making an pendulum animation which has an image which should move along x-axis when the phone is tilted upto a certain degree and return to its original state when the phone is held straight.

Here's what i have done:-

Main.Java

 public class MainActivity extends Activity implements SensorEventListener
    {

         protected void onCreate(Bundle savedInstanceState)
            {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_main);

                imgPend= (ImageView)findViewById(R.id.imgBell);

                sensorManager= (SensorManager) getSystemService(SENSOR_SERVICE);
                lastUpdate = System.currentTimeMillis();


                rAnimation= new RotateAnimation(0.0f, 30.0f,
                        Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
                        0.5f);

                rAnimation.setFillAfter(true);
        }
@Override
    public void onSensorChanged(SensorEvent event) 
    {
        // TODO Auto-generated method stub
        if(event.sensor.getType() == Sensor.TYPE_ACCELEROMETER)
            getAccelerometer(event);
    }






    private void getAccelerometer(SensorEvent event)
    {
        // TODO Auto-generated method stub
        float[] values = event.values;

        float x = values[0];
        float y = values[1];
    //  float z = values[2];

          float accelationSquareRoot = (x * x + y * y )//+ z * z)
                    / (SensorManager.GRAVITY_EARTH * SensorManager.GRAVITY_EARTH);
                long actualTime = System.currentTimeMillis();
                if (accelationSquareRoot >= 2) //
                {
                  if (actualTime - lastUpdate < 200) 
                  {
                    return;
                  }
                  lastUpdate = actualTime;
                  rAnimation= new RotateAnimation(0.0f, 30.0f,
                            Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
                            0.5f);

                  rAnimation.setFillAfter(true);
                  rAnimation.setRepeatMode(rAnimation.REVERSE);


                  imgPend.startAnimation(rAnimation);

                }         
    }

The issue is that the animation is not very smooth and happens only when i shake the phone. I want it to be smooth with just a tilt and back.

¿Fue útil?

Solución

I think you should try

 rAnimation.setRepeatCount(rAnimation.RESTART);

Otros consejos

if (actualTime - lastUpdate < 200)

Here you're essentially allowing 5FPS. Reduce this to 50ms or so to get smoother animation.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top