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 trueprivate long delay; // To give thread consistencyprivate int currentX, currentY; // To hold current position of the 'X'private int width; // To hold screen widthprivate int height; // To hold screen heightprivate Sprite spriteTank; // our sprite!// Constructor and initializationpublic 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 looppublic void start() {isPlay = true;new Thread(this).start();}public void stop() { isPlay = false; }// Main Game Looppublic void run() {Graphics g = getGraphics();while (isPlay) {input();drawScreen(g);try {Thread.sleep(delay);}catch (InterruptedException ie) {}}}// Method to Handle User Inputsprivate void input() {int keyStates = getKeyStates();// Leftif ((keyStates & LEFT_PRESSED) != 0) {currentX = Math.max(0, currentX - 1);spriteTank.setFrame(INDEX_OF_LEFT);}// Rightif ((keyStates & RIGHT_PRESSED) !=0 ) {if ( currentX + 5
运行后的画面如下,可以用上下左右控制坦克: