游戲的基礎是動畫,想來大家都知道。這幾天公司的項目都忙完了。很是無聊,所以就上網找了些資源,並寫兩個動畫的例子。在此貼出來,讓大家把磚頭砸我吧。^_^
J2ME midp2.0有個game的包是用來設計有游戲用的。它供給了游戲設計的基礎控件,比如雙緩沖,精靈,圖層把持器等基礎設施,這些設施可以方便我們的設計,比如雙緩沖可以讓游戲履行流暢,精靈等,可以更好的把持角色。
說白了。動畫的後果實在就是一幅幅圖片按照指定的時間一幅幅的換圖片而已。
好了。看代碼吧。
Java 代碼
package org.wuhua.game.timer;
import Java.util.Timer;
- import Java.util.TimerTask;
- /** * 對Timer的包裝
- * @author wuhua
*/
- public class TimerTaskManager { private Timer _timer;
static TimerTaskManager instace;
public static TimerTaskManager getInstace() {
- if (instace == null) instace = new TimerTaskManager();
- return instace; }
public TimerTask add(Runnable runnable, long period) {
- TimerTask task = new RunnableTimerTask(runnable); long delay = period;
- getTimer().schedule(task, delay, period); return task;
- }
- 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 Runnable _runnable;
- RunnableTimerTask(Runnable runnable) { _runnable = runnable;
- }
- public void run() { _runnable.run();
- } }
- }
Java 代碼
package org.wuhua.game;
import Java.io.IOException;
- import Java.util.TimerTask;
- import Javax.microedition.lcdui.Canvas; import Javax.microedition.lcdui.Graphics;
- import Javax.microedition.lcdui.Image;
- import org.wuhua.game.timer.TimerTaskManager;
- /** * 動畫的主類
- * @author wuhua
*/
- public class Game extends Canvas implements Runnable{
- private Image source; private Image action[] = new Image[10];
- private int bgcolor = 0x209C00; private TimerTask task;
- private static int next; Game(){
- try { source = Image.createImage("/action.png");
- } catch (IOException e) {
- e.printStackTrace(); }
- //切割圖片 for(int i=0; i<5; i++){
- action[i] = Image.createImage(source, 96*i, 0, 96, 60, 0); }
for(int j=5; j<10; j++){
- action[j] = Image.createImage(source, 96*(j-5), 102, 96, 80, 0); }
//這個是用來執舉動作的計時器。原理是請求經過0.2毫秒動一次
- task = TimerTaskManager.getInstace().add(this, 150); }
- protected void paint(Graphics g) { fillScreen(g);
- paintAction(g);
- } private void fillScreen(Graphics g) {
- g.setColor(0xFFFFFF); g.fillRect(0, 0, this.getWidth(), this.getHeight());
}
- private void paintAction(Graphics g) { if(next == 10)
- next =0; //假如繪制的圖片是出雷電的時候,讓人物停留在那裡。這樣的後果會好點
- if(next>=5){ g.drawImage(action[4], 10*4, 0, Graphics.LEFT|Graphics.TOP);
- } g.drawImage(action[next], 10*next, 0, Graphics.LEFT|Graphics.TOP);
- next++;
- } public void run() {
- repaint();
- }
- }