Sprite 專為遊戲動畫角色設計(飛機、坦克等)。MIDP 1.0 需自行實作,MIDP 2.0 內建強力支援,可建立靜態/動態、透明/不透明 Sprite。
Sprite(Image):單圖 Sprite。Sprite(Image, int width, int height):動畫 Sprite,圖片依指定大小切割為多幀,透過 setFrame(int index) 切換動畫。使用 64x16 透明背景 PNG(含 4 個 16x16 幀:上、右、左、下),在 Eclipse 建立專案結構。(原文含圖片)
package tank.midp.core;
import javax.microedition.lcdui.*;
import javax.microedition.lcdui.game.*;
public class TankGameCanvas extends GameCanvas implements Runnable {
private static final int INDEX_OF_UP = 0, INDEX_OF_DOWN = 1, INDEX_OF_RIGHT = 2, INDEX_OF_LEFT = 3;
private boolean isPlay;
private long delay = 20;
private int currentX, currentY, width, height;
private Sprite spriteTank;
public TankGameCanvas() {
super(true);
width = getWidth(); height = getHeight();
currentX = width/2; currentY = height/2;
try {
Image img = Image.createImage("/res/img/player1.png");
spriteTank = new Sprite(img, 16, 16);
} catch (Exception e) { e.printStackTrace(); }
}
public void start() { isPlay = true; new Thread(this).start(); }
public void stop() { isPlay = false; }
public void run() {
Graphics g = getGraphics();
while (isPlay) {
input();
drawScreen(g);
try { Thread.sleep(delay); } catch (InterruptedException ie) {}
}
}
private void input() {
int keyStates = getKeyStates();
if ((keyStates & LEFT_PRESSED) != 0) {
currentX = Math.max(0, currentX - 1);
spriteTank.setFrame(INDEX_OF_LEFT);
}
if ((keyStates & RIGHT_PRESSED) != 0) {
if (currentX + 5 < width) currentX = Math.min(width, currentX + 1);
spriteTank.setFrame(INDEX_OF_RIGHT);
}
if ((keyStates & UP_PRESSED) != 0) {
currentY = Math.max(0, currentY - 1);
spriteTank.setFrame(INDEX_OF_UP);
}
if ((keyStates & DOWN_PRESSED) != 0) {
if (currentY + 10 < height) currentY = Math.min(height, currentY + 1);
spriteTank.setFrame(INDEX_OF_DOWN);
}
}
private void drawScreen(Graphics g) {
g.setColor(0); g.fillRect(0, 0, getWidth(), getHeight());
spriteTank.setPosition(currentX, currentY);
spriteTank.paint(g);
flushGraphics();
}
}