滚球在Android中使用Accelerometer
我有两个isses - 球离开界限 - 球移动不平稳(看起来它消失了,再次出现在屏幕上)这里是我的代码
公共类GameActivity扩展活动{
私人GameView GameView;
私人SensorManager sensorManager;
私人传感器加速计;
public static Timer tmr;
public static TimerTask tsk = null;
public static Handler handler = new Handler();
公共静态可运行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/74939.html上一篇: Rolling ball use Accelerometer in Android
下一篇: Android PagerAdapter destroyItem(), caches for a while when using fragments