CLDC 1.0 不支援浮點運算,MathFP 以 32 位整數模擬 16.16 定點格式,提供 sin/cos/tan、sqrt、矩陣等數學函數,體積極小(單一 MathFP.class),是 J2ME 遊戲物理、軌跡計算的首選。
int fp = MathFP.toFP(intVal)MathFP.add/sub/mul/div/fpValint i = MathFP.toInt(fpVal)(向零取整)MathFP.PI、MathFP.E 等均為定點表示。屏幕左下角起點,每 100ms 以速率 5 像素沿 60° 方向移動,繪製軌跡線。
public class FloatCanvas extends Canvas implements Runnable {
int w_FP, h_FP, curX_FP, curY_FP, lastX_FP, lastY_FP;
static final int RATE = 5;
int paintCount = 0;
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) {
// 60度 -> 弧度
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 ignored) {}
lastX_FP = curX_FP; lastY_FP = curY_FP;
}
}
}
軌跡呈直線向右上延伸。有了定點三角函數,可實現:旋轉精靈、彈道計算、簡單物理引擎(重力、反射)、向量內積/外積等。
https://home.rochester.rr.com/ohoms/MathFP(版本 1.1.2)。net.jscience.util.MathFP.class 放入 classpath 或反編譯為源碼置入 src/。