Android加速感应器开发平衡球代码解析
2011-01-05 10:14:17 来源:本站整理如何使用Android的加速感应器开发一个控制铁球滚动的游戏:
public class AccelerometerPlayActivity extends Activity {
private SimulationView mSimulationView; //游戏主显示View
private SensorManager mSensorManager; //感应器管理类
private PowerManager mPowerManager; //电源控制,比如防锁屏
private WindowManager mWindowManager;
private Display mDisplay;
private WakeLock mWakeLock;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE); // 实例化感应器管理类
mPowerManager = (PowerManager) getSystemService(POWER_SERVICE);
mWindowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
mDisplay = mWindowManager.getDefaultDisplay(); //为了获取屏幕的DPI级别
mWakeLock = mPowerManager.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, getClass()
.getName()); //处理屏幕防止锁屏
mSimulationView = new SimulationView(this);
setContentView(mSimulationView); //设置游戏View
}
@Override
protected void onResume() {
super.onResume();
mWakeLock.acquire(); //恢复时解除锁屏
mSimulationView.startSimulation();
}
@Override
protected void onPause() {
super.onPause();
mSimulationView.stopSimulation(); //Activity切出去时停止画面更新
mWakeLock.release();
}
class SimulationView extends View implements SensorEventListener {
private static final float sBallDiameter = 0.004f; //设置小球直径
private static final float sBallDiameter2 = sBallDiameter * sBallDiameter;
private static final float sFriction = 0.1f; //摩擦系数
private Sensor mAccelerometer;
private long mLastT;
private float mLastDeltaT;
private float mXDpi;
private float mYDpi;
private float mMetersToPixelsX;
private float mMetersToPixelsY;
private Bitmap mBitmap; //小球素材
private Bitmap mWood; //背景使用木头
private float mXOrigin;
private float mYOrigin;
private float mSensorX;
private float mSensorY;
private long mSensorTimeStamp;
private long mCpuTimeStamp;
private float mHorizontalBound;
private float mVerticalBound;
private final ParticleSystem mParticleSystem = new ParticleSystem();
class Particle {
private float mPosX;
private float mPosY;
private float mAccelX;
private float mAccelY;
private float mLastPosX;
private float mLastPosY;
private float mOneMinusFriction;
- ››Android 当修改一些代码时,使用什么编译命令可以最...
- ››Android 如何添加一个apk使模拟器和真机都编译进去...
- ››Android 修改Camera拍照的默认保存路径
- ››Android 如何修改默认输入法
- ››android开发中finish()和System.exit(0)的区别
- ››Android手势识别简单封装类
- ››android中查看项目数字证书的两种方法
- ››Android中获取IMEI码的办法
- ››android 相机报错 setParameters failed
- ››Android重启运用程序的代码
- ››Android为ListView的Item设置不同的布局
- ››android bitmap与base64字符串的互相转换
更多精彩
赞助商链接