Rolling ball use Accelerometer in Android

i have two isses - the ball is going out of bound of the screen - the ball movement is not smooth ( looks it disappears and re appears on the screen) here is my code

public class GameActivity extends Activity{

private GameView GameView;

private SensorManager sensorManager;

private Sensor accelerometer;

public static Timer tmr;

public static TimerTask tsk = null;

public static Handler handler = new Handler();

public static Runnable runnable;

int mScrWidth, mScrHeight;

android.graphics.PointF mBallPos, mBallSpd;

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getWindow().setFlags(0xFFFFFFFF,LayoutParams.FLAG_FULLSCREEN||LayoutParams.FLAG_KEEP_SCREEN_ON);
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_game);

    GameView = (GameView) findViewById(R.id.gameView);

    // Add sensor listener
    // Set the screen always portrait
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

    sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);

    accelerometer = sensorManager
            .getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
    setVolumeControlStream(AudioManager.STREAM_MUSIC);

    // get screen dimensions
    Display display = getWindowManager().getDefaultDisplay();

    mScrWidth = display.getWidth();
    mScrHeight = display.getHeight();
    mBallPos = new android.graphics.PointF();
    mBallSpd = new android.graphics.PointF();

    // create variables for ball position and speed
    mBallPos.x = mScrWidth / 2;
    mBallPos.y = mScrHeight / 2;
    mBallSpd.x = 0;
    mBallSpd.y = 0;

    // listener for accelerometer, use anonymous class for simplicity
    ((SensorManager) getSystemService(Context.SENSOR_SERVICE))
            .registerListener(new SensorEventListener() {
                @Override
                public void onSensorChanged(SensorEvent event) {
                    // set ball speed based on phone tilt (ignore Z axis)
                    mBallSpd.x =-event.values[0];
                    mBallSpd.y = event.values[1];
                    // timer event will redraw ball

                }

                @Override
                public void onAccuracyChanged(Sensor sensor, int accuracy) {
                } // ignore this event
            }, ((SensorManager) getSystemService(Context.SENSOR_SERVICE))
                    .getSensorList(Sensor.TYPE_ACCELEROMETER).get(0),
                    SensorManager.SENSOR_DELAY_NORMAL);
}

}

链接地址: http://www.djcxy.com/p/74940.html

上一篇: 如何检索json嵌套数组数据并填充到listview中?

下一篇: 滚球在Android中使用Accelerometer