WEB开发网
开发学院手机开发Android 开发 Android加速感应器开发平衡球代码解析 阅读

Android加速感应器开发平衡球代码解析

 2011-01-05 10:14:17 来源:本站整理   
核心提示:如何使用Android的加速感应器开发一个控制铁球滚动的游戏:public class AccelerometerPlayActivity extends Activity { private SimulationView mSimulationView; //游戏主显示View private SensorMan

如何使用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;

1 2 3 4 5 6  下一页

Tags:Android 加速 感应器

编辑录入:coldstar [复制链接] [打 印]
赞助商链接