編輯:Android 遊戲開發
寫 Android 遊戲時,多數直覺是「抓最新版 SDK 就對了」,但我反而常用 1.5、1.6 這類舊版本來開發。原因其實很務實。
首先,Android SDK 是向下相容的。能在低版本跑起來的程式,放到高版本機器上幾乎不會出問題;反過來則不然。其次,低版本能覆蓋更多老機型,等於把可觸及的使用者基盤拉大。
還有一個更關鍵的理由:新版 SDK 的底層通常更成熟、效能更好。同一款遊戲在舊機上會卡,換到新機就順順的——但這也形成一個陷阱。如果你一開始就用高版本開發,你根本看不出自己的程式在效能與記憶體上真實的表現如何;用低版本開發,反而會逼你把每一幀、每一次配置都寫得夠精實。等它在舊版本上都跑得順,換到新機器自然是享受。
結論:只要遊戲不需要更新的 API,以 SDK 1.5/1.6 為基準開發是很值得推薦的選擇。
上一篇談的是觸控手勢,但那終究只是系統把一組觸屏動作包裝好丟給你。真正有意思的是「輸入法手勢辨識」——也就是手機九宮格解鎖、畫個字母啟動 App 背後的那套技術。手勢是你自己定義的,系統只負責比對。
把這東西放進遊戲裡會很好玩:畫一個圓形換背景,畫一個 X 退出遊戲,畫個三角形開啟隱藏關卡。玩家會覺得這遊戲「有靈魂」。

本篇要掌握兩件事:
name(對應的手勢名稱)與 score(相似度)。另外要理解「筆畫」這個概念——它和寫字的筆畫是同一回事。筆畫類型有兩種:

畫面由上到下是 TextView、EditText,接著是一個 RelativeLayout,裡頭疊了自訂的 SurfaceView 與鋪滿全屏的 GestureOverlayView。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id="@+id/himi_tv"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="15sp"
android:textColor="#FFFFFF00" />
<EditText
android:id="@+id/himi_edit"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1">
<com.himi.MySurfaceView
android:id="@+id/view3d"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
<android.gesture.GestureOverlayView
android:id="@+id/himi_gesture"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1.0" />
</RelativeLayout>
</LinearLayout>
GestureOverlayView 這裡只定義了寬高,其餘重要屬性我放在程式碼裡設定,XML 當然也做得到。
/**
* 輸入法手勢辨識
* 注意:android.gesture 這個套件從 API 4(SDK 1.6)才開始支援。
* 提醒:手勢預設存到 SD 卡,別忘了在 AndroidManifest.xml 加上讀寫權限!
*/
public class MainActivity extends Activity {
private GestureOverlayView gov; // 手寫繪圖區
private Gesture gesture; // 手寫 instance
private GestureLibrary gestureLib;// 手勢倉庫
private TextView tv;
private EditText et;
private String path; // 手勢檔路徑
private File file;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
tv = (TextView) findViewById(R.id.himi_tv);
et = (EditText) findViewById(R.id.himi_edit);
gov = (GestureOverlayView) findViewById(R.id.himi_gesture);
// 筆畫類型:改成 GESTURE_STROKE_TYPE_SINGLE 就只吃單一筆畫
gov.setGestureStrokeType(GestureOverlayView.GESTURE_STROKE_TYPE_MULTIPLE);
path = new File(Environment.getExternalStorageDirectory(), "gestures").getAbsolutePath();
file = new File(path);
gestureLib = GestureLibraries.fromFile(path);
gov.addOnGestureListener(new OnGestureListener() {
// 開始畫手勢時觸發
@Override
public void onGestureStarted(GestureOverlayView overlay, MotionEvent event) {
tv.setText("請在緊接的時間內用兩筆畫完成一個手勢!");
}
// 手勢形成時觸發
@Override
public void onGestureEnded(GestureOverlayView overlay, MotionEvent event) {
gesture = overlay.getGesture();
if (gesture.getStrokesCount() == 2) {
if (event.getAction() == MotionEvent.ACTION_UP) {
if (et.getText().toString().equals("")) {
tv.setText("你沒有輸入手勢名稱,儲存失敗。");
} else {
tv.setText("正在儲存手勢…");
addMyGesture(et.getText().toString(), gesture);
}
}
} else {
tv.setText("請在緊接的時間內用兩筆畫完成一個手勢!");
}
}
@Override public void onGestureCancelled(GestureOverlayView o, MotionEvent e) {}
@Override public void onGesture(GestureOverlayView o, MotionEvent e) {}
});
if (!gestureLib.load()) {
tv.setText("第一次載入,先來練習畫幾個手勢吧!操作:先在 EditText 輸入名稱,再畫手勢。");
} else {
Set<String> set = gestureLib.getGestureEntries();
loadAllGesture(set, set.toArray());
}
}
}
我把建立手勢、比對手勢、遍歷手勢、手勢轉圖片這幾件事各自拉成獨立函式,思路會清楚很多。
理論上,設定成多筆畫之後,系統應該要等你停手一段時間才判定手勢完成。實測卻不是這樣:不管你設定的類型是單一還是多筆畫,只要手指離開螢幕,Android 就會立刻觸發 onGestureEnded——即使你只寫了兩筆中的第一筆。
解法是 gesture.getStrokesCount()。它會回報這段時間內你畫了幾筆,而單一筆畫模式下這個值永遠不會大於 1。用這個值當條件,就能過濾掉「手指還沒離開就被誤判」的情況。
public void addMyGesture(String name, Gesture gesture) {
try {
if (name.equals("himi")) {
findGesture(gesture); // 名稱是 himi 就走比對流程
} else {
if (Environment.getExternalStorageState() != null) {
if (!file.exists()) {
// 手勢檔不存在:直接寫入倉庫後存檔
gestureLib.addGesture(name, gesture);
if (gestureLib.save()) {
gov.clear(true);
gestureToImage(gesture);
et.setText("");
} else {
tv.setText("儲存手勢失敗!");
}
} else {
// 手勢檔已存在:先讀回來,同名就移除舊的,再寫入新的
if (!gestureLib.load()) {
tv.setText("手勢檔讀取失敗!");
} else {
Set<String> set = gestureLib.getGestureEntries();
Object ob[] = set.toArray();
boolean isHavedGesture = false;
for (int i = 0; i < ob.length; i++) {
if (((String) ob[i]).equals(name)) isHavedGesture = true;
}
if (isHavedGesture) {
gestureLib.removeEntry(name); // 連 key 一起刪掉
gestureLib.addGesture(name, gesture);
} else {
gestureLib.addGesture(name, gesture);
}
if (gestureLib.save()) {
gov.clear(true);
gestureToImage(gesture);
et.setText("");
}
}
}
} else {
tv.setText("目前裝置沒有 SD 卡。");
}
}
} catch (Exception e) {
tv.setText("操作異常!");
}
}
整體套路和 File 存檔一樣:先看 SD 卡有沒有,再看檔案有沒有。檔案不存在就乾脆地寫進倉庫並 save();檔案存在就必須先 load() 讀回內容,處理同名衝突後再存。
關於刪除的兩種寫法,值得說清楚:
gestureLib.removeGesture(name, gesture) 只移掉手勢本身,名稱這個 key 還留在 HashMap 裡。下次同名手勢寫入時,會直接覆蓋該條目的 value。gestureLib.removeEntry(name) 則是把整個條目(key 與 value)一起刪掉。因為底層就是 HashMap(key = 手勢名稱,value = 手勢),其實同名情況下你連刪除都可以省略,直接 addGesture 就會自動覆蓋。
public void gestureToImage(Gesture ges) {
if (MySurfaceView.vec_bmp != null) {
MySurfaceView.vec_bmp.addElement(
ges.toBitmap(100, 100, 12, Color.GREEN));
}
}
public void loadAllGesture(Set<String> set, Object ob[]) {
if (gestureLib.load()) {
set = gestureLib.getGestureEntries();
ob = set.toArray();
for (int i = 0; i < ob.length; i++) {
gestureToImage(gestureLib.getGestures((String) ob[i]).get(0));
MySurfaceView.vec_string.addElement((String) ob[i]);
}
}
}
public void findGesture(Gesture gesture) {
try {
if (Environment.getExternalStorageState() != null) {
if (!file.exists()) {
tv.setText("比對失敗:手勢檔不存在。");
} else if (!gestureLib.load()) {
tv.setText("比對失敗:手勢檔讀取失敗。");
} else {
// recognize() 回傳所有可能的匹配結果
List<Prediction> predictions = gestureLib.recognize(gesture);
if (!predictions.isEmpty()) {
Prediction prediction = predictions.get(0);
// score 代表相似度,實務上通常忽略 score < 1 的結果
if (prediction.score >= 1) {
tv.setText("最相似的手勢:name = " + prediction.name);
}
}
}
} else {
tv.setText("比對失敗:目前裝置沒有 SD 卡。");
}
} catch (Exception e) {
e.printStackTrace();
tv.setText("發生異常,比對失敗。");
}
}
核心就是 recognize():它回傳一個 Prediction 集合,裡面可能有多個相似的候選,第一個通常就是最佳解,再用 score 決定要不要採信。
不論是觸控手勢還是輸入法手勢,放進遊戲裡都能讓操作層次整個升級。自訂手勢的門檻其實不高,但玩家感受到的「這遊戲很懂我」卻非常強烈,值得花時間做。
Android遊戲引擎libgdx使用教學13:在TiledMap地圖中加入角色與移動控制
本文承接上一篇(libgdx使用教學12:如何使用TiledMap地圖)。地圖建好之後,接下來就是讓主角登場。由於前面已經介紹過 TiledMap 與 Stage 的結合
Android 遊戲開發 21:裝置解析度被縮放的原因與解法
問題現象 建立解析度為 800×480 的模擬器時,程式取得的螢幕寬高卻可能是 320×533。這是因為 Android 1.6 之後加入多螢幕支援,系統會依 Densi
Android遊戲開發實戰(十五):重力感應控制小球
重力感應的核心,其實就是手機裡的加速度傳感器(accelerometer)。Android平台一共提供了八類傳感器,
Android遊戲開發實戰(十七):橫屏與豎屏的切換技巧
只要玩過Android手機,對「橫豎屏」這套機制應該都不陌生。仔細觀察你手機裡的遊戲,會發現大多數作品都被鎖死在單一方向上:有的只能豎著握,有的必須橫過來玩,真正允許自由