J2ME中定点库MathFP使用入门
http://tech.ddvip.com 2007年11月22日 社区交流
本文详细介绍J2ME中定点库MathFP使用入门
import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Graphics;
import net.jscience.util.MathFP;
/**
* 小数运算演示Canvas
* @author Jagie
*
*/
public class FloatCanvas
extends Canvas implements Runnable
{
//用于统计屏幕刷新次数
int paintCount;
//屏幕宽度,高度。定点数
int w_FP, h_FP;
//当前点坐标,前一点坐标,定点数
int curX_FP, curY_FP,
lastX_FP, lastY_FP;
//速率
public static final int RATE = 5;
public FloatCanvas()
{
w_FP = MathFP.toFP(this.getWidth());
h_FP = MathFP.toFP(this.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, w_FP, h_FP);
}
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));
//x方向增量
int deltaX = MathFP.mul(MathFP.toFP(RATE),
MathFP.cos(radians));
//y方向增量
int deltaY = MathFP.mul(MathFP.toFP(RATE),
MathFP.sin(radians));
//新坐标,定点数
curX_FP = lastX_FP + deltaX;
curY_FP = lastY_FP - deltaY;
System.out.println(curX_FP + "," + curY_FP);
repaint();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//新坐标成为旧坐标
lastX_FP = curX_FP;
lastY_FP = curY_FP;
}
}
}
该Canvas在设备上绘制效果如下图:

大家可以看到,曲线正沿60度角的方向朝东北方向不停的增长。有了这个定点库,我们就能在游戏中使用小数运算了,所以一些简单的游戏物理算法也可以使用了。
作者:Jagie 责编:豆豆技术应用