首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> J2ME

J2ME 遊戲動畫基礎:Timer 排程與影格切換實作

     編輯:J2ME

前言

遊戲核心在於動畫。MIDP 2.0 javax.microedition.game 套件提供雙緩衝、精靈、圖層管理等基礎設施。本文展示兩個核心類別:TimerTaskManager (單例計時器) 與 Game (動畫主邏輯)。

TimerTaskManager:統一計時器管理

public class TimerTaskManager {
    private Timer timer;
    private static TimerTaskManager instance;

    public static TimerTaskManager getInstance() {
        if (instance == null) instance = new TimerTaskManager();
        return instance;
    }

    public TimerTask add(Runnable task, long period) {
        TimerTask tt = new RunnableTimerTask(task);
        timer.schedule(tt, period, period);
        return tt;
    }

    public void close() {
        if (timer != null) { timer.cancel(); timer = null; }
    }

    private Timer getTimer() {
        if (timer == null) timer = new Timer();
        return timer;
    }

    static class RunnableTimerTask extends TimerTask {
        private final Runnable runnable;
        RunnableTimerTask(Runnable r) { runnable = r; }
        public void run() { runnable.run(); }
    }
}

Game Canvas:動畫主邏輯

public class Game extends Canvas implements Runnable {
    private Image source;
    private Image[] frames = new Image[10];
    private int bgColor = 0x209C00;
    private TimerTask animTask;
    private static int frameIndex = 0;

    public Game() {
        try { source = Image.createImage("/action.png"); }
        catch (IOException e) { e.printStackTrace(); }

        // 從單張大圖切割 10 個影格 (5 格跑步 + 5 格雷電)
        for (int i = 0; i < 5; i++)
            frames[i] = Image.createImage(source, 96*i, 0, 96, 60, 0);
        for (int j = 5; j < 10; j++)
            frames[j] = Image.createImage(source, 96*(j-5), 102, 96, 80, 0);

        // 每 150ms 切換一次影格
        animTask = TimerTaskManager.getInstance().add(this, 150);
    }

    protected void paint(Graphics g) {
        fillScreen(g);
        paintAction(g);
    }

    private void fillScreen(Graphics g) {
        g.setColor(0xFFFFFF);
        g.fillRect(0, 0, getWidth(), getHeight());
    }

    private void paintAction(Graphics g) {
        if (frameIndex == 10) frameIndex = 0;
        // 雷電動作 (索引 5-9) 期間,保持跑步第 5 格 (索引 4) 不動
        if (frameIndex >= 5)
            g.drawImage(frames[4], 40, 0, Graphics.LEFT | Graphics.TOP);
        g.drawImage(frames[frameIndex], frameIndex*10, 0, Graphics.LEFT | Graphics.TOP);
        frameIndex++;
    }

    public void run() { repaint(); }  // Timer 呼叫
}

關鍵技術點

  1. 圖集:單張 PNG 包含所有影格,Image.createImage(source, x, y, w, h, transform) 切割,減少檔案數與載入開銷。
  2. Timer 驅動:TimerTaskManager 封裝 Timer,避免重複建立計時器,統一管理週期任務。
  3. 雙緩衝:Canvas 繼承自 GameCanvas 可啟用雙緩衝 (setFullScreenMode),消除閃爍。
  4. 影格邏輯:frameIndex 循環 0-9,雷電階段固定顯示跑步末影格,形成「跑步→雷電→跑步」循環。

結語

掌握「圖集切割 + Timer 週期觸發 + 影格索引邏輯」即可實現流暢 2D 動畫,為進階遊戲開發 (精靈、碰撞、圖層) 打下基礎。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved