sprite,精灵,顾名思义,专用来代表游戏中的动画角色,比如飞机,坦克等等。在midp1.0中,我们必须自己写专门的类来实现sprite,幸运的是,midp2.0为sprite提供了强力支持,可以创建静态,动态,不透明和透明的sprite,下面我们准备在上次的gamecanvas基础上添加一个sprite并让它动起来。
sprite的主要构造方法有:
sprite(image):构造一个单幅图案的sprite;
sprite(image, int width, int height):构造一个动画sprite,图片将按照指定大小被分为n个frame,通过setframe(int index)就可以让sprite动起来。我们用了一个有透明背景的png图片创建坦克的sprite:

(注意这个图是放大的jpg格式,你需要用photoshop之类的软件处理成有透明背景的png格式,大小为64x16)
我们在eclipse中建立如下工程和目录:

以下是画出sprite的tankgamecanvas.java:
package tank.midp.core;import javax.microedition.lcdui.*;import javax.microedition.lcdui.game.*;public class tankgamecanvas extends gamecanvas implements runnable { // 控制方向: private static int index_of_up = 0; private static int index_of_down = 1; private static int index_of_left = 3; private static int index_of_right = 2; private boolean isplay; // game loop runs when isplay is true private long delay; // to give thread consistency private int currentx, currenty; // to hold current position of the 'x' private int width; // to hold screen width private int height; // to hold screen height private sprite spritetank; // our sprite! // constructor and initialization public tankgamecanvas() { super(true); width = getwidth(); height = getheight(); currentx = width / 2; currenty = height / 2; delay = 20; // init sprite: try { image image = image.createimage("/res/img/player1.png"); // 注意路径 spritetank = new sprite(image, 16, 16); // 大小是16x16 } catch(exception e) { e.printstacktrace(); } } // automatically start thread for game loop public void start() { isplay = true; new thread(this).start(); } public void stop() { isplay = false; } // main game loop public void run() { graphics g = getgraphics(); while (isplay) { input(); drawscreen(g); try { thread.sleep(delay); } catch (interruptedexception ie) {} } } // method to handle user inputs private void input() { int keystates = getkeystates(); // left if ((keystates & left_pressed) != 0) { currentx = math.max(0, currentx - 1); spritetank.setframe(index_of_left); } // right if ((keystates & right_pressed) !=0 ) { if ( currentx + 5 < width) currentx = math.min(width, currentx + 1); spritetank.setframe(index_of_right); } // up if ((keystates & up_pressed) != 0) { currenty = math.max(0, currenty - 1); spritetank.setframe(index_of_up); } // down if ((keystates & down_pressed) !=0) { if ( currenty + 10 < height) currenty = math.min(height, currenty + 1); spritetank.setframe(index_of_down); } } // method to display graphics private void drawscreen(graphics g) { g.setcolor(0); // black g.fillrect(0, 0, getwidth(), getheight()); // 画一个sprite非常简单: spritetank.setposition(currentx, currenty); spritetank.paint(g); flushgraphics(); }}
运行后的画面如下,可以用上下左右控制坦克:

闽公网安备 35060202000074号