Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 遊戲 >> Android 遊戲開發

Android 遊戲開發教程(八):以 LunarLander 實例掌握 SurfaceView

編輯:Android 遊戲開發

如果說 Android 遊戲開發有什麼是「非學不可」的核心知識,SurfaceView 絕對榜上有名。它之所以重要,是因為遊戲的畫面往往需要高頻率地不斷重繪,而傳統的 View 在這方面力有未逮。SurfaceView 提供了獨立的繪製表面與專屬的繪製執行緒,正是流暢動畫的基礎。

要理解 SurfaceView,最好的方式不是死背 API,而是拆解一個真實作品。Android SDK 內建了一個經典範例——LunarLander(登陸月球)小遊戲,它的 LunarView 幾乎把 SurfaceView 的精髓展露無遺。以下就讓我們透過原始碼,看看一個完整的遊戲視圖是如何運作的。

建議的學習方法是:先把這個範例專案匯入 Eclipse,編譯、執行、親手玩幾局,感受一下操作手感;然後再對照著下面的程式碼逐段研讀。這樣「先動手、再理解」的順序,往往比一頭栽進程式碼來得有效。以下是程式碼:

  1. class LunarView extends SurfaceView implements SurfaceHolder.Callback {
  2.     class LunarThread extends Thread {
  3.         /*
  4.          * Difficulty setting constants
  5.          */
  6.         public static final int DIFFICULTY_EASY = 0;
  7.         public static final int DIFFICULTY_HARD = 1;
  8.         public static final int DIFFICULTY_MEDIUM = 2;
  9.         /*
  10.          * Physics constants
  11.          */
  12.         public static final int PHYS_DOWN_ACCEL_SEC = 35;
  13.         public static final int PHYS_FIRE_ACCEL_SEC = 80;
  14.         public static final int PHYS_FUEL_INIT = 60;
  15.         public static final int PHYS_FUEL_MAX = 100;
  16.         public static final int PHYS_FUEL_SEC = 10;
  17.         public static final int PHYS_SLEW_SEC = 120; // degrees/second rotate
  18.         public static final int PHYS_SPEED_HYPERSPACE = 180;
  19.         public static final int PHYS_SPEED_INIT = 30;
  20.         public static final int PHYS_SPEED_MAX = 120;
  21.         /*
  22.          * State-tracking constants
  23.          */
  24.         public static final int STATE_LOSE = 1;
  25.         public static final int STATE_PAUSE = 2;
  26.         public static final int STATE_READY = 3;
  27.         public static final int STATE_RUNNING = 4;
  28.         public static final int STATE_WIN = 5;
  29.  
  30.         /*
  31.          * Goal condition constants
  32.          */
  33.         public static final int TARGET_ANGLE = 18; // > this angle means crash
  34.         public static final int TARGET_BOTTOM_PADDING = 17; // px below gear
  35.         public static final int TARGET_PAD_HEIGHT = 8; // how high above ground
  36.         public static final int TARGET_SPEED = 28; // > this speed means crash
  37.         public static final double TARGET_WIDTH = 1.6; // width of target
  38.         /*
  39.          * UI constants (i.e. the speed & fuel bars)
  40.          */
  41.         public static final int UI_BAR = 100; // width of the bar(s)
  42.         public static final int UI_BAR_HEIGHT = 10; // height of the bar(s)
  43.         private static final String KEY_DIFFICULTY = "mDifficulty";
  44.         private static final String KEY_DX = "mDX";
  45.  
  46.         private static final String KEY_DY = "mDY";
  47.         private static final String KEY_FUEL = "mFuel";
  48.         private static final String KEY_GOAL_ANGLE = "mGoalAngle";
  49.         private static final String KEY_GOAL_SPEED = "mGoalSpeed";
  50.         private static final String KEY_GOAL_WIDTH = "mGoalWidth";
  51.  
  52.         private static final String KEY_GOAL_X = "mGoalX";
  53.         private static final String KEY_HEADING = "mHeading";
  54.         private static final String KEY_LANDER_HEIGHT = "mLanderHeight";
  55.         private static final String KEY_LANDER_WIDTH = "mLanderWidth";
  56.         private static final String KEY_WINS = "mWinsInARow";
  57.  
  58.         private static final String KEY_X = "mX";
  59.         private static final String KEY_Y = "mY";
  60.  
  61.         /*
  62.          * Member (state) fields
  63.          */
  64.         /** The drawable to use as the background of the animation canvas */
  65.         private Bitmap mBackgroundImage;
  66.  
  67.         /**
  68.          * Current height of the surface/canvas.
  69.          *
  70.          * @see #setSurfaceSize
  71.          */
  72.         private int mCanvasHeight = 1;
  73.  
  74.         /**
  75.          * Current width of the surface/canvas.
  76.          *
  77.          * @see #setSurfaceSize
  78.          */
  79.         private int mCanvasWidth = 1;
  80.  
  81.         /** What to draw for the Lander when it has crashed */
  82.         private Drawable mCrashedImage;
  83.  
  84.         /**
  85.          * Current difficulty -- amount of fuel, allowed angle, etc. Default is
  86.          * MEDIUM.
  87.          */
  88.         private int mDifficulty;
  89.  
  90.         /** Velocity dx. */
  91.         private double mDX;
  92.  
  93.         /** Velocity dy. */
  94.         private double mDY;
  95.  
  96.         /** Is the engine burning? */
  97.         private boolean mEngineFiring;
  98.  
  99.         /** What to draw for the Lander when the engine is firing */
  100.         private Drawable mFiringImage;
  101.  
  102.         /** Fuel remaining */
  103.         private double mFuel;
  104.  
  105.         /** Allowed angle. */
  106.         private int mGoalAngle;
  107.  
  108.         /** Allowed speed. */
  109.         private int mGoalSpeed;
  110.  
  111.         /** Width of the landing pad. */
  112.         private int mGoalWidth;
  113.  
  114.         /** X of the landing pad. */
  115.         private int mGoalX;
  116.  
  117.         /** Message handler used by thread to interact with TextView */
  118.         private Handler mHandler;
  119.  
  120.         /**
  121.          * Lander heading in degrees, with 0 up, 90 right. Kept in the range
  122.          * 0..360.
  123.          */
  124.         private double mHeading;
  125.  
  126.         /** Pixel height of lander image. */
  127.         private int mLanderHeight;
  128.  
  129.         /** What to draw for the Lander in its normal state */
  130.         private Drawable mLanderImage;
  131.  
  132.         /** Pixel width of lander image. */
  133.         private int mLanderWidth;
  134.  
  135.         /** Used to figure out elapsed time between frames */
  136.         private long mLastTime;
  137.  
  138.         /** Paint to draw the lines on screen. */
  139.         private Paint mLinePaint;
  140.  
  141.         /** "Bad" speed-too-high variant of the line color. */
  142.         private Paint mLinePaintBad;
  143.  
  144.         /** The state of the game. One of READY, RUNNING, PAUSE, LOSE, or WIN */
  145.         private int mMode;
  146.  
  147.         /** Currently rotating, -1 left, 0 none, 1 right. */
  148.         private int mRotating;
  149.  
  150.         /** Indicate whether the surface has been created & is ready to draw */
  151.         private boolean mRun = false;
  152.  
  153.         /** Scratch rect object. */
  154.         private RectF mScratchRect;
  155.  
  156.         /** Handle to the surface manager object we interact with */
  157.         private SurfaceHolder mSurfaceHolder;
  158.  
  159.         /** Number of wins in a row. */
  160.         private int mWinsInARow;
  161.  
  162.         /** X of lander center. */
  163.         private double mX;
  164.  
  165.         /** Y of lander center. */
  166.         private double mY;
  167.  
  168.         public LunarThread(SurfaceHolder surfaceHolder, Context context,
  169.                   Handler handler) {
  170.             // get handles to some important objects
  171.             mSurfaceHolder = surfaceHolder;
  172.             mHandler = handler;
  173.             mContext = context;
  174.  
  175.             Resources res = context.getResources();
  176.             // cache handles to our key sprites & other drawables
  177.             mLanderImage = context.getResources().getDrawable(
  178.                     R.drawable.lander_plain);
  179.             mFiringImage = context.getResources().getDrawable(
  180.                     R.drawable.lander_firing);
  181.             mCrashedImage = context.getResources().getDrawable(
  182.                     R.drawable.lander_crashed);
  183.  
  184.             // load background image as a Bitmap instead of a Drawable b/c
  185.             // we don't need to transform it and it's faster to draw this way
  186.             mBackgroundImage = BitmapFactory.decodeResource(res,
  187.                     R.drawable.earthrise);
  188.  
  189.             // Use the regular lander image as the model size for all sprites
  190.             mLanderWidth = mLanderImage.getIntrinsicWidth();
  191.             mLanderHeight = mLanderImage.getIntrinsicHeight();
  192.  
  193.             // Initialize paints for speedometer
  194.             mLinePaint = new Paint();
  195.             mLinePaint.setAntiAlias(true);
  196.             mLinePaint.setARGB(255, 0, 255, 0);
  197.  
  198.             mLinePaintBad = new Paint();
  199.             mLinePaintBad.setAntiAlias(true);
  200.             mLinePaintBad.setARGB(255, 120, 180, 0);
  201.  
  202.             mScratchRect = new RectF(0, 0, 0, 0);
  203.  
  204.             mWinsInARow = 0;
  205.             mDifficulty = DIFFICULTY_MEDIUM;
  206.  
  207.             // initial show-up of lander (not yet playing)
  208.             mX = mLanderWidth;
  209.             mY = mLanderHeight * 2;
  210.             mFuel = PHYS_FUEL_INIT;
  211.             mDX = 0;
  212.             mDY = 0;
  213.             mHeading = 0;
  214.             mEngineFiring = true;
  215.         }
  216.  
  217.         /**
  218.          * Starts the game, setting parameters for the current difficulty.
  219.          */
  220.         public void doStart() {
  221.             synchronized (mSurfaceHolder) {
  222.                 // First set the game for Medium difficulty
  223.                 mFuel = PHYS_FUEL_INIT;
  224.                 mEngineFiring = false;
  225.                 mGoalWidth = (int) (mLanderWidth * TARGET_WIDTH);
  226.                 mGoalSpeed = TARGET_SPEED;
  227.                 mGoalAngle = TARGET_ANGLE;
  228.                 int speedInit = PHYS_SPEED_INIT;
  229.  
  230.                 // Adjust difficulty params for EASY/HARD
  231.                 if (mDifficulty == DIFFICULTY_EASY) {
  232.                     mFuel = mFuel * 3 / 2;
  233.                     mGoalWidth = mGoalWidth * 4 / 3;
  234.                     mGoalSpeed = mGoalSpeed * 3 / 2;
  235.                     mGoalAngle = mGoalAngle * 4 / 3;
  236.                     speedInit = speedInit * 3 / 4;
  237.                  } else if (mDifficulty == DIFFICULTY_HARD) {
  238.                     mFuel = mFuel * 7 / 8;
  239.                     mGoalWidth = mGoalWidth * 3 / 4;
  240.                     mGoalSpeed = mGoalSpeed * 7 / 8;
  241.                     speedInit = speedInit * 4 / 3;
  242.                  }
  243.  
  244.                 // pick a convenient initial location for the lander sprite
  245.                 mX = mCanvasWidth / 2;
  246.                 mY = mCanvasHeight - mLanderHeight / 2;
  247.  
  248.                 // start with a little random motion
  249.                 mDY = Math.random() * -speedInit;
  250.                 mDX = Math.random() * 2 * speedInit - speedInit;
  251.                 mHeading = 0;
  252.  
  253.                 // Figure initial spot for landing, not too near center
  254.                 while (true) {
  255.                     mGoalX = (int) (Math.random() * (mCanvasWidth - mGoalWidth));
  256.                     if (Math.abs(mGoalX - (mX - mLanderWidth / 2)) > mCanvasHeight / 6)
  257.                         break;
  258.                  }
  259.  
  260.                 mLastTime = System.currentTimeMillis() + 100;
  261.                 setState(STATE_RUNNING);
  262.              }
  263.         }
  264.  
  265.         /**
  266.          * Pauses the physics update & animation.
  267.          */
  268.         public void pause() {
  269.             synchronized (mSurfaceHolder) {
  270.                 if (mMode == STATE_RUNNING) setState(STATE_PAUSE);
  271.              }
  272.         }
  273.  
  274.         /**
  275.          * Restores game state from the indicated Bundle. Typically called when
  276.          * the Activity is being restored after having been previously
  277.          * destroyed.
  278.          *
  279.          * @param savedState Bundle containing the game state
  280.          */
  281.         public synchronized void restoreState(Bundle savedState) {
  282.             synchronized (mSurfaceHolder) {
  283.                 setState(STATE_PAUSE);
  284.                 mRotating = 0;
  285.                 mEngineFiring = false;
  286.  
  287.                 mDifficulty = savedState.getInt(KEY_DIFFICULTY);
  288.                 mX = savedState.getDouble(KEY_X);
  289.                 mY = savedState.getDouble(KEY_Y);
  290.                 mDX = savedState.getDouble(KEY_DX);
  291.                 mDY = savedState.getDouble(KEY_DY);
  292.                 mHeading = savedState.getDouble(KEY_HEADING);
  293.  
  294.                 mLanderWidth = savedState.getInt(KEY_LANDER_WIDTH);
  295.                 mLanderHeight = savedState.getInt(KEY_LANDER_HEIGHT);
  296.                 mGoalX = savedState.getInt(KEY_GOAL_X);
  297.                 mGoalSpeed = savedState.getInt(KEY_GOAL_SPEED);
  298.                 mGoalAngle = savedState.getInt(KEY_GOAL_ANGLE);
  299.                 mGoalWidth = savedState.getInt(KEY_GOAL_WIDTH);
  300.                 mWinsInARow = savedState.getInt(KEY_WINS);
  301.                 mFuel = savedState.getDouble(KEY_FUEL);
  302.              }
  303.         }
  304.  
  305.         @Override
  306.         public void run() {
  307.             while (mRun) {
  308.                 Canvas c = null;
  309.                 try {
  310.                     c = mSurfaceHolder.lockCanvas(null);
  311.                     synchronized (mSurfaceHolder) {
  312.                         if (mMode == STATE_RUNNING) updatePhysics();
  313.                         doDraw(c);
  314.                      }
  315.                 } finally {
  316.                     // do this in a finally so that if an exception is thrown
  317.                     // during the above, we don't leave the Surface in an
  318.                     // inconsistent state
  319.                     if (c != null) {
  320.                         mSurfaceHolder.unlockCanvasAndPost(c);
  321.                      }
  322.                  }
  323.             }
  324.         }
  325.  
  326.         /**
  327.          * Dump game state to the provided Bundle. Typically called when the
  328.          * Activity is being suspended.
  329.          *
  330.          * @return Bundle with this view's state
  331.          */
  332.         public Bundle saveState(Bundle map) {
  333.             synchronized (mSurfaceHolder) {
  334.                 if (map != null) {
  335.                     map.putInt(KEY_DIFFICULTY, Integer.valueOf(mDifficulty));
  336.                     map.putDouble(KEY_X, Double.valueOf(mX));
  337.                     map.putDouble(KEY_Y, Double.valueOf(mY));
  338.                     map.putDouble(KEY_DX, Double.valueOf(mDX));
  339.                     map.putDouble(KEY_DY, Double.valueOf(mDY));
  340.                     map.putDouble(KEY_HEADING, Double.valueOf(mHeading));
  341.                     map.putInt(KEY_LANDER_WIDTH, Integer.valueOf(mLanderWidth));
  342.                     map.putInt(KEY_LANDER_HEIGHT, Integer
  343.                             .valueOf(mLanderHeight));
  344.                     map.putInt(KEY_GOAL_X, Integer.valueOf(mGoalX));
  345.                     map.putInt(KEY_GOAL_SPEED, Integer.valueOf(mGoalSpeed));
  346.                     map.putInt(KEY_GOAL_ANGLE, Integer.valueOf(mGoalAngle));
  347.                     map.putInt(KEY_GOAL_WIDTH, Integer.valueOf(mGoalWidth));
  348.                     map.putInt(KEY_WINS, Integer.valueOf(mWinsInARow));
  349.                     map.putDouble(KEY_FUEL, Double.valueOf(mFuel));
  350.                  }
  351.              }
  352.             return map;
  353.         }
  354.  
  355.         /**
  356.          * Sets the current difficulty.
  357.          *
  358.          * @param difficulty
  359.          */
  360.         public void setDifficulty(int difficulty) {
  361.             synchronized (mSurfaceHolder) {
  362.                 mDifficulty = difficulty;
  363.              }
  364.         }
  365.  
  366.         /**
  367.          * Sets if the engine is currently firing.
  368.         */
  369.         public void setFiring(boolean firing) {
  370.             synchronized (mSurfaceHolder) {
  371.                 mEngineFiring = firing;
  372.              }
  373.         }
  374.  
  375.         /**
  376.          * Used to signal the thread whether it should be running or not.
  377.          * Passing true allows the thread to run; passing false will shut it
  378.          * down if it's already running. Calling start() after this was most
  379.          * recently called with false will result in an immediate shutdown.
  380.          *
  381.          * @param b true to run, false to shut down
  382.          */
  383.         public void setRunning(boolean b) {
  384.             mRun = b;
  385.         }
  386.  
  387.         /**
  388.          * Sets the game mode. That is, whether we are running, paused, in the
  389.          * failure state, in the victory state, etc.
  390.          *
  391.          * @see #setState(int, CharSequence)
  392.          * @param mode one of the STATE_* constants
  393.          */
  394.         public void setState(int mode) {
  395.             synchronized (mSurfaceHolder) {
  396.                 setState(mode, null);
  397.              }
  398.         }
  399.  
  400.         /**
  401.          * Sets the game mode. That is, whether we are running, paused, in the
  402.          * failure state, in the victory state, etc.
  403.          *
  404.          * @param mode one of the STATE_* constants
  405.          * @param message string to add to screen or null
  406.          */
  407.         public void setState(int mode, CharSequence message) {
  408.             /*
  409.              * This method optionally can cause a text message to be displayed
  410.              * to the user when the mode changes. Since the View that actually
  411.              * renders that text is part of the main View hierarchy and not
  412.              * owned by this thread, we can't touch the state of that View.
  413.              * Instead we use a Message + Handler to relay commands to the main
  414.              * thread, which updates the user-text View.
  415.             */
  416.             synchronized (mSurfaceHolder) {
  417.                 mMode = mode;
  418.  
  419.                 if (mMode == STATE_RUNNING) {
  420.                     Message msg = mHandler.obtainMessage();
  421.                     Bundle b = new Bundle();
  422.                     b.putString("text", "");
  423.                     b.putInt("viz", View.INVISIBLE);
  424.                     msg.setData(b);
  425.                     mHandler.sendMessage(msg);
  426.                  } else {
  427.                     mRotating = 0;
  428.                     mEngineFiring = false;
  429.                     Resources res = mContext.getResources();
  430.                     CharSequence str = "";
  431.                     if (mMode == STATE_READY)
  432.                         str = res.getText(R.string.mode_ready);
  433.                     else if (mMode == STATE_PAUSE)
  434.                         str = res.getText(R.string.mode_pause);
  435.                     else if (mMode == STATE_LOSE)
  436.                         str = res.getText(R.string.mode_lose);
  437.                     else if (mMode == STATE_WIN)
  438.                         str = res.getString(R.string.mode_win_prefix)
  439.                             + mWinsInARow + " "
  440.                             + res.getString(R.string.mode_win_suffix);
  441.  
  442.                     if (message != null) {
  443.                         str = message + "\n" + str;
  444.                      }
  445.  
  446.                     if (mMode == STATE_LOSE) mWinsInARow = 0;
  447.  
  448.                     Message msg = mHandler.obtainMessage();
  449.                     Bundle b = new Bundle();
  450.                     b.putString("text", str.toString());
  451.                     b.putInt("viz", View.VISIBLE);
  452.                     msg.setData(b);
  453.                     mHandler.sendMessage(msg);
  454.                  }
  455.              }
  456.         }
  457.  
  458.         /* Callback invoked when the surface dimensions change. */
  459.         public void setSurfaceSize(int width, int height) {
  460.             // synchronized to make sure these all change atomically
  461.             synchronized (mSurfaceHolder) {
  462.                 mCanvasWidth = width;
  463.                 mCanvasHeight = height;
  464.  
  465.                 // don't forget to resize the background image
  466.                 mBackgroundImage = mBackgroundImage.createScaledBitmap(
  467.                         mBackgroundImage, width, height, true);
  468.              }
  469.         }
  470.  
  471.         /**
  472.          * Resumes from a pause.
  473.          */
  474.         public void unpause() {
  475.             // Move the real time clock up to now
  476.             synchronized (mSurfaceHolder) {
  477.                 mLastTime = System.currentTimeMillis() + 100;
  478.              }
  479.         setState(STATE_RUNNING);
  480.         }
  481.  
  482.         /**
  483.          * Handles a key-down event.
  484.          *
  485.          * @param keyCode the key that was pressed
  486.          * @param msg the original event object
  487.          * @return true
  488.          */
  489.         boolean doKeyDown(int keyCode, KeyEvent msg) {
  490.             synchronized (mSurfaceHolder) {
  491.                 boolean okStart = false;
  492.                 if (keyCode == KeyEvent.KEYCODE_DPAD_UP) okStart = true;
  493.                 if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN) okStart = true;
  494.                 if (keyCode == KeyEvent.KEYCODE_S) okStart = true;
  495.  
  496.                 boolean center = (keyCode == KeyEvent.KEYCODE_DPAD_UP);
  497.  
  498.                 if (okStart
  499.                         && (mMode == STATE_READY || mMode == STATE_LOSE || mMode == STATE_WIN)) {
  500.                     // ready-to-start -> start
  501.                     doStart();
  502.                     return true;
  503.                  } else if (mMode == STATE_PAUSE && okStart) {
  504.                     // paused -> running
  505.                     unpause();
  506.                     return true;
  507.                  } else if (mMode == STATE_RUNNING) {
  508.                     // center/space -> fire
  509.                     if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER
  510.                         || keyCode == KeyEvent.KEYCODE_SPACE) {
  511.                         setFiring(true);
  512.                         return true;
  513.                         // left/q -> left
  514.                      } else if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT
  515.                         || keyCode == KeyEvent.KEYCODE_Q) {
  516.                     mRotating = -1;
  517.                     return true;
  518.                     // right/w -> right
  519.                     } else if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT
  520.                         || keyCode == KeyEvent.KEYCODE_W) {
  521.                     mRotating = 1;
  522.                     return true;
  523.                     // up -> pause
  524.                     } else if (keyCode == KeyEvent.KEYCODE_DPAD_UP) {
  525.                     pause();
  526.                     return true;
  527.                  }
  528.  
  529.                 return false;
  530.              }
  531.         }
  532.  
  533.         /**
  534.          * Handles a key-up event.
  535.          *
  536.          * @param keyCode the key that was pressed
  537.          * @param msg the original event object
  538.          * @return true if the key was handled and consumed, or else false
  539.          */
  540.         boolean doKeyUp(int keyCode, KeyEvent msg) {
  541.             boolean handled = false;
  542.  
  543.             synchronized (mSurfaceHolder) {
  544.                 if (mMode == STATE_RUNNING) {
  545.                     if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER
  546.                         || keyCode == KeyEvent.KEYCODE_SPACE) {
  547.                         setFiring(false);
  548.                         handled = true;
  549.                      } else if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT
  550.                         || keyCode == KeyEvent.KEYCODE_Q
  551.                         || keyCode == KeyEvent.KEYCODE_DPAD_RIGHT
  552.                         || keyCode == KeyEvent.KEYCODE_W) {
  553.                     mRotating = 0;
  554.                     handled = true;
  555.                  }
  556.              }
  557.              }
  558.  
  559.             return handled;
  560.         }
  561.  
  562.         /**
  563.          * Draws the ship, fuel/speed bars, and background to the provided
  564.          * Canvas.
  565.          */
  566.         private void doDraw(Canvas canvas) {
  567.             // Draw the background image. Operations on the Canvas accumulate
  568.             // so this is like clearing the screen.
  569.             canvas.drawBitmap(mBackgroundImage, 0, 0, null);
  570.  
  571.             int yTop = mCanvasHeight - ((int) mY + mLanderHeight / 2);
  572.             int xLeft = (int) mX - mLanderWidth / 2;
  573.  
  574.             // Draw the fuel gauge
  575.             int fuelWidth = (int) (UI_BAR * mFuel / PHYS_FUEL_MAX);
  576.             mScratchRect.set(4, 4, 4 + fuelWidth, 4 + UI_BAR_HEIGHT);
  577.             canvas.drawRect(mScratchRect, mLinePaint);
  578.  
  579.             // Draw the speed gauge, with a two-tone effect
  580.             double speed = Math.sqrt(mDX * mDX + mDY * mDY);
  581.             int speedWidth = (int) (UI_BAR * speed / PHYS_SPEED_MAX);
  582.  
  583.             if (speed <= mGoalSpeed) {
  584.                 mScratchRect.set(4 + UI_BAR + 4, 4,
  585.                         4 + UI_BAR + 4 + speedWidth, 4 + UI_BAR_HEIGHT);
  586.                 canvas.drawRect(mScratchRect, mLinePaint);
  587.              } else {
  588.                 // Draw the bad color in back, with the good color in front of
  589.                 // it
  590.                 mScratchRect.set(4 + UI_BAR + 4, 4,
  591.                         4 + UI_BAR + 4 + speedWidth, 4 + UI_BAR_HEIGHT);
  592.                 canvas.drawRect(mScratchRect, mLinePaintBad);
  593.                 int goalWidth = (UI_BAR * mGoalSpeed / PHYS_SPEED_MAX);
  594.                 mScratchRect.set(4 + UI_BAR + 4, 4, 4 + UI_BAR + 4 + goalWidth,
  595.                         4 + UI_BAR_HEIGHT);
  596.                 canvas.drawRect(mScratchRect, mLinePaint);
  597.              }
  598.  
  599.             // Draw the landing pad
  600.             canvas.drawLine(mGoalX, 1 + mCanvasHeight - TARGET_PAD_HEIGHT,
  601.                     mGoalX + mGoalWidth, 1 + mCanvasHeight - TARGET_PAD_HEIGHT,
  602.                     mLinePaint);
  603.  
  604.             // Draw the ship with its current rotation
  605.             canvas.save();
  606.             canvas.rotate((float) mHeading, (float) mX, mCanvasHeight
  607.                     - (float) mY);
  608.             if (mMode == STATE_LOSE) {
  609.                 mCrashedImage.setBounds(xLeft, yTop, xLeft + mLanderWidth, yTop
  610.                     + mLanderHeight);
  611.                 mCrashedImage.draw(canvas);
  612.              } else if (mEngineFiring) {
  613.                 mFiringImage.setBounds(xLeft, yTop, xLeft + mLanderWidth, yTop
  614.                     + mLanderHeight);
  615.                 mFiringImage.draw(canvas);
  616.              } else {
  617.                 mLanderImage.setBounds(xLeft, yTop, xLeft + mLanderWidth, yTop
  618.                     + mLanderHeight);
  619.                 mLanderImage.draw(canvas);
  620.              }
  621.             canvas.restore();
  622.         }
  623.  
  624.         /**
  625.          * Figures the lander state (x, y, fuel, ...) based on the passage of
  626.          * realtime. Does not invalidate(). Called at the start of draw().
  627.          * Detects the end-of-game and sets the UI to the next state.
  628.          */
  629.         private void updatePhysics() {
  630.             long now = System.currentTimeMillis();
  631.  
  632.             // Do nothing if mLastTime is in the future.
  633.             // This allows the game-start to delay the start of the physics
  634.             // by 100ms or whatever.
  635.             if (mLastTime > now) return;
  636.  
  637.             double elapsed = (now - mLastTime) / 1000.0;
  638.  
  639.             // mRotating -- update heading
  640.             if (mRotating != 0) {
  641.                 mHeading += mRotating * (PHYS_SLEW_SEC * elapsed);
  642.  
  643.                 // Bring things back into the range 0..360
  644.                 if (mHeading < 0)
  645.                     mHeading += 360;
  646.                 else if (mHeading >= 360) mHeading -= 360;
  647.              }
  648.  
  649.             // Base accelerations -- 0 for x, gravity for y
  650.             double ddx = 0.0;
  651.             double ddy = -PHYS_DOWN_ACCEL_SEC * elapsed;
  652.  
  653.             if (mEngineFiring) {
  654.                 // taking 0 as up, 90 as to the right
  655.                 // cos(deg) is ddy component, sin(deg) is ddx component
  656.                 double elapsedFiring = elapsed;
  657.                 double fuelUsed = elapsedFiring * PHYS_FUEL_SEC;
  658.  
  659.                 // tricky case where we run out of fuel partway through the
  660.                 // elapsed
  661.                 if (fuelUsed > mFuel) {
  662.                     elapsedFiring = mFuel / fuelUsed * elapsed;
  663.                     fuelUsed = mFuel;
  664.  
  665.                     // Oddball case where we adjust the "control" from here
  666.                     mEngineFiring = false;
  667.                  }
  668.  
  669.                 mFuel -= fuelUsed;
  670.  
  671.                 // have this much acceleration from the engine
  672.                 double accel = PHYS_FIRE_ACCEL_SEC * elapsedFiring;
  673.  
  674.                 double radians = 2 * Math.PI * mHeading / 360;
  675.                 ddx = Math.sin(radians) * accel;
  676.                 ddy += Math.cos(radians) * accel;
  677.              }
  678.  
  679.             double dxOld = mDX;
  680.             double dyOld = mDY;
  681.  
  682.             // figure speeds for the end of the period
  683.             mDX += ddx;
  684.             mDY += ddy;
  685.  
  686.             // figure position based on average speed during the period
  687.             mX += elapsed * (mDX + dxOld) / 2;
  688.             mY += elapsed * (mDY + dyOld) / 2;
  689.  
  690.             mLastTime = now;
  691.  
  692.             // Evaluate if we have landed ... stop the game
  693.             double yLowerBound = TARGET_PAD_HEIGHT + mLanderHeight / 2
  694.                     - TARGET_BOTTOM_PADDING;
  695.             if (mY <= yLowerBound) {
  696.                 mY = yLowerBound;
  697.  
  698.                 int result = STATE_LOSE;
  699.                 CharSequence message = "";
  700.                 Resources res = mContext.getResources();
  701.                 double speed = Math.sqrt(mDX * mDX + mDY * mDY);
  702.                 boolean onGoal = (mGoalX <= mX - mLanderWidth / 2 && mX
  703.                     + mLanderWidth / 2 <= mGoalX + mGoalWidth);
  704.  
  705.                 // "Hyperspace" win -- upside down, going fast,
  706.                 // puts you back at the top.
  707.                 if (onGoal && Math.abs(mHeading - 180) < mGoalAngle
  708.                     && speed > PHYS_SPEED_HYPERSPACE) {
  709.                     result = STATE_WIN;
  710.                     mWinsInARow++;
  711.                     doStart();
  712.  
  713.                     return;
  714.                     // Oddball case: this case does a return, all other cases
  715.                     // fall through to setMode() below.
  716.                  } else if (!onGoal) {
  717.                     message = res.getText(R.string.message_off_pad);
  718.                  } else if (!(mHeading <= mGoalAngle || mHeading >= 360 - mGoalAngle)) {
  719.                     message = res.getText(R.string.message_bad_angle);
  720.                  } else if (speed > mGoalSpeed) {
  721.                     message = res.getText(R.string.message_too_fast);
  722.                  } else {
  723.                     result = STATE_WIN;
  724.                     mWinsInARow++;
  725.                  }
  726.  
  727.                 setState(result, message);
  728.              }
  729.         }
  730.  
  731.     /** Handle to the application context, used to e.g. fetch Drawables. */
  732.     private Context mContext;
  733.  
  734.     /** Pointer to the text view to display "Paused.." etc. */
  735.     private TextView mStatusText;
  736.  
  737.     /** The thread that actually draws the animation */
  738.     private LunarThread thread;
  739.  
  740.     public LunarView(Context context, AttributeSet attrs) {
  741.         super(context, attrs);
  742.  
  743.         // register our interest in hearing about changes to our surface
  744.         SurfaceHolder holder = getHolder();
  745.         holder.addCallback(this);
  746.  
  747.         // create thread only; it's started in surfaceCreated()
  748.         thread = new LunarThread(holder, context, new Handler() {
  749.             @Override
  750.             public void handleMessage(Message m) {
  751.                 mStatusText.setVisibility(m.getData().getInt("viz"));
  752.                 mStatusText.setText(m.getData().getString("text"));
  753.              }
  754.         });
  755.  
  756.         setFocusable(true); // make sure we get key events
  757.     }
  758.  
  759.     /**
  760.      * Fetches the animation thread corresponding to this LunarView.
  761.      *
  762.      * @return the animation thread
  763.     */
  764.     public LunarThread getThread() {
  765.         return thread;
  766.     }
  767.  
  768.     /**
  769.      * Standard override to get key-press events.
  770.     */
  771.     @Override
  772.     public boolean onKeyDown(int keyCode, KeyEvent msg) {
  773.         return thread.doKeyDown(keyCode, msg);
  774.     }
  775.  
  776.     /**
  777.      * Standard override for key-up. We actually care about these, so we can
  778.      * turn off the engine or stop rotating.
  779.     */
  780.     @Override
  781.     public boolean onKeyUp(int keyCode, KeyEvent msg) {
  782.         return thread.doKeyUp(keyCode, msg);
  783.     }
  784.  
  785.     /**
  786.      * Standard window-focus override. Notice focus lost so we can pause on
  787.      * focus lost. e.g. user switches to take a call.
  788.     */
  789.     @Override
  790.     public void onWindowFocusChanged(boolean hasWindowFocus) {
  791.         if (!hasWindowFocus) thread.pause();
  792.     }
  793.  
  794.     /**
  795.      * Installs a pointer to the text view used for messages.
  796.     */
  797.     public void setTextView(TextView textView) {
  798.         mStatusText = textView;
  799.     }
  800.  
  801.     /* Callback invoked when the surface dimensions change. */
  802.     public void surfaceChanged(SurfaceHolder holder, int format, int width,
  803.             int height) {
  804.         thread.setSurfaceSize(width, height);
  805.     }
  806.  
  807.     /*
  808.  * Callback invoked when the Surface has been created and is ready to be
  809.  * used.
  810.  */
  811.     public void surfaceCreated(SurfaceHolder holder) {
  812.         // start the thread here so that we don't busy-wait in run()
  813.         // waiting for the surface to be created
  814.         thread.setRunning(true);
  815.         thread.start();
  816.     }
  817.  
  818.     /*
  819.  * Callback invoked when the Surface has been destroyed and must no longer
  820.  * be touched. WARNING: after this method returns, the Surface/Canvas must
  821.  * never be touched again!
  822.  */
  823.     public void surfaceDestroyed(SurfaceHolder holder) {
  824.         // we have to tell thread to shut down & wait for it to finish, or else
  825.         // it might touch the Surface after we return and explode
  826.         boolean retry = true;
  827.         thread.setRunning(false);
  828.         while (retry) {
  829.             try {
  830.                 thread.join();
  831.                 retry = false;
  832.              } catch (InterruptedException e) {
  833.              }
  834.         }
  835.     }
  836. }

這段程式碼為什麼值得細讀?

LunarLander 之所以是學習 SurfaceView 的經典範本,是因為它把遊戲開發的幾個核心環節都示範得淋漓盡致。首先是 「繪製與運算分離」:LunarView 負責管理畫面與事件,而真正一幀一幀重繪的則是獨立的 LunarThread。這個執行緒透過 run() 方法不斷地 lockCanvas、更新物理狀態、繪製、再 unlockCanvasAndPost,形成一個標準的遊戲主迴圈。

其次是 生命週期管理。三個關鍵回呼——surfaceCreated、surfaceChanged、surfaceDestroyed——精準地對應了繪製表面的誕生、尺寸變化與銷毀。特別值得注意的是 surfaceDestroyed 裡那段「先通知執行緒停止、再用 join() 等它結束」的寫法,正是為了避免執行緒在表面消失後仍去碰它而導致崩潰。這個細節,是所有使用 SurfaceView 的開發者都該牢記的鐵律。

再者,時間差驅動的物理模擬也相當精彩。updatePhysics() 透過計算兩帧之間的 elapsed 時間,來推算重力、推力與位移,讓遊戲在不同效能的裝置上都能維持一致的節奏,而不是依賴固定的帧率。這種以「真實時間」為基準的思路,是現代遊戲引擎的通用做法。

最後,別忘了它還示範了如何用 Handler 與 Message 進行執行緒間通訊——當遊戲狀態改變(例如準備、暫停、勝利、失敗)時,工作執行緒並不能直接操作屬於主執行緒的 TextView,而是透過訊息把更新請求轉交給主執行緒處理。理解這一點,你就能避開多執行緒環境下最常見的崩潰陷阱。

把這些模式吃透,你手上就不只是一個登陸小遊戲,而是一套可以套用到任何動作遊戲的穩固骨架。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved