on(params);
if(type != Camera.GENERIC) {
//计算窗口的宽高比
float waspect=viewport_width/viewport_height;
if (waspectfloat height = viewport_width/params[1];
viewport_height=(int)height;
viewport_y=(myCanvas.getHeight()-viewport_height)/2;
}
else {
float width = viewport_height*params[1];
viewport_width=(int)width;
viewport_x=(myCanvas.getWidth()-viewport_width)/2;
}
}
}
七、刷新视图
为了刷新视图,你可以用TimerTask来调用画布的repaint()方法。另一种方法是直接使用线程,然后创建ExampleCanvas(画布类的名字)来实现Runnable接口。
列表4. 刷新视图
private class RefreshTask extends TimerTask
{
public void run(){
if(myCanvas != null && myGraphics3D != null && myWorld != null) {
int startTime = (int)System.currentTimeMillis();
int validity = myWorld.animate(startTime);
myCanvas.repaint(viewport_x, viewport_y, viewport_width,
viewport_height);
}
}
}
八、完整的例程代码分析
在列表5中,你会看到应用程序的完整代码。虽然长些,但是比Sun的例子要简单许多。你可以通过给应用程序添加上一些动作和逻辑来练习你的MIDP技能。
列表5. 完整的例程代码
package com.kontio;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import java.lang.IllegalArgumentException;
import java.io.*;
import java.util.*;
import javax.microedition.m3g.*;
public class Example3D extends MIDlet implements CommandListener{
//我们在场景中使用的对象的UserID
static final int POGOROO = 554921620;
static final int CAMERA = 769302310;
static final int TRANSFORM = 347178853;
static final int ROO = 418071423;
private Display myDisplay = null;
private ExampleCanvas myCanvas = null;
private Timer myRefreshTimer = new Timer();
private TimerTask myRefreshTask = null;
private Command exitCommand = new Command("Exit", Command.ITEM, 1);
Graphics3D myGraphics3D = Graphics3D.getInstance();
World myWorld = null;
private AnimationController animRoo = null;
private Group tRoo = null;
private Group tCams = null;
private Group acRoo = null;
private int animLength = 0;
int viewport_x;
int viewport_y;
int viewport_width;
int viewport_height;
public Example3D(){
super();
myDisplay = Display.getDisplay(this);
myCanvas = new ExampleCanvas(this);
myCanvas.setCommandListener(this);
myCanvas.addCommand(exitCommand);
}
public void startApp() throws MIDletStateChangeException{
myDisplay.setCurrent(myCanvas);
try{
// 从文件中加载World
myWorld = (World)Loader.load("/pogoroo.m3g")[0];
getObjects();
setupAspectRatio();
}
catch(Exception e){
e.printStackTrace();
}
myRefreshTask = new RefreshTask();
// 调度一个重要执行的计时器以显示出帧速率20fps.
myRefreshTimer.schedule(myRefreshTask, 0, 50);
}
void setupAspectRatio(){
viewport_x = 0;
viewport_y = 0;
viewport_width = myCanvas.getWidth();
viewport_height = myCanvas.getHeight();
Camera cam = myWorld.getActiveCamera();
float[] params = new float[4];
int type = cam.getProjection(params);
if(type != Camera.GENERIC){
//计算窗口的宽高比例
float waspect=viewport_width/viewport_height;
if (waspectfloa
|