CLDC 1.0 不支援浮點運算,導致早期 Java ME 裝置無法直接處理小數。MathFP 以整數模擬定點運算,成為 J2ME 環境下小數計算的最佳解決方案——體積小、效能高、API 完整。本文將從原理到實戰,帶您快速上手。
MathFP 將小數以 整數形式儲存,內部採用 16.16 定點格式(高 16 位整數部、低 16 位小數部)。開發者需遵守鐵律:
「參與運算的整數必須先轉為定點數(toFP),運算完成後再轉回整數(toInt)使用。」
命名建議:定點數變數以 _FP 為後綴(如 x_FP),避免與純整數混淆。
MathFP.class(套件 net.jscience.util),官網:MathFP 專案頁。src 目錄。模擬一點每 100ms 以 5 像素速度沿 60° 方向移動,需用三角函數計算增量:
RATE * cos(60°)RATE * sin(60°)import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Graphics;
import net.jscience.util.MathFP;
public class FloatCanvas extends Canvas implements Runnable {
int paintCount;
int w_FP, h_FP; // 螢幕寬高(定點數)
int curX_FP, curY_FP; // 當前座標
int lastX_FP, lastY_FP; // 前一座標
public static final int RATE = 5; // 速率 5 像素
public FloatCanvas() {
w_FP = MathFP.toFP(getWidth());
h_FP = MathFP.toFP(getHeight());
lastX_FP = MathFP.toFP(0);
lastY_FP = h_FP; // 左下角起始
new Thread(this).start();
}
protected void paint(Graphics g) {
if (paintCount == 0) {
g.setColor(0);
g.fillRect(0, 0, getWidth(), getHeight());
} else {
g.setColor(0x00FF00);
// 定點數轉整數繪製線段
g.drawLine(MathFP.toInt(lastX_FP), MathFP.toInt(lastY_FP),
MathFP.toInt(curX_FP), MathFP.toInt(curY_FP));
}
paintCount++;
}
public void run() {
while (curX_FP <= w_FP && curY_FP <= h_FP &&
MathFP.toInt(curX_FP) >= 0 && MathFP.toInt(curY_FP) >= 0) {
// 角度轉弧度:radians = 60 * PI / 180
int radians = MathFP.div(MathFP.mul(MathFP.toFP(60), MathFP.PI),
MathFP.toFP(180));
// 計算增量
int deltaX = MathFP.mul(MathFP.toFP(RATE), MathFP.cos(radians));
int deltaY = MathFP.mul(MathFP.toFP(RATE), MathFP.sin(radians));
// 更新座標
curX_FP = lastX_FP + deltaX;
curY_FP = lastY_FP - deltaY; // Y 軸向下為正
repaint();
try { Thread.sleep(100); } catch (InterruptedException e) {}
lastX_FP = curX_FP;
lastY_FP = curY_FP;
}
}
}
| MathFP 方法 | 對應數學運算 | 範例 |
|---|---|---|
toFP(int) | 整數 → 定點數 | MathFP.toFP(5) |
toInt(int) | 定點數 → 整數(截斷) | MathFP.toInt(x_FP) |
add/sub/mul/div | 基本四則運算 | MathFP.mul(a_FP, b_FP) |
sin/cos/tan | 三角函數(參數為弧度定點數) | MathFP.sin(rad_FP) |
PI | π 常數(定點數) | MathFP.PI |
有了 MathFP,J2ME 遊戲即可實現:物理拋物線、向量旋轉、碰撞檢測、粒子系統等進階算法,突破「唯有整數」的限制。