⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 mycanvas.java

📁 J2ME手机游戏开发技术详解随书光盘
💻 JAVA
字号:
// Any use of this code and/or information below is subject to the
// license terms: http://wireless.java.sun.com/berkeley_license.html

import java.io.IOException;

import javax.microedition.lcdui.*;
import javax.microedition.lcdui.game.*;
//MicroTankCanvas 扩展GameCanvas引用Runnable接口

public class MyCanvas    extends GameCanvas    implements Runnable {
  private boolean isRun;//声明一个布尔变量mTrucking
  private Sprite mTank;
  private int curX = 0,curY = 0;
  private int canvasWidth,canvasHeight;
  private int AniCounter = 0;
  private int mDirection = 0;
  private static final int[] kFrameLookup = {
    0, 1, 2, 
    0, 1, 2, 
    0, 1, 2, 
    0, 1, 2, 
    };//12
    private static final int[] kTransformLookup = {//旋转位置矩阵
    Sprite.TRANS_NONE, Sprite.TRANS_NONE, Sprite.TRANS_NONE,
    Sprite.TRANS_ROT90, Sprite.TRANS_ROT90, Sprite.TRANS_ROT90,
    Sprite.TRANS_ROT180, Sprite.TRANS_ROT180, Sprite.TRANS_ROT180,
    Sprite.TRANS_ROT270, Sprite.TRANS_ROT270, Sprite.TRANS_ROT270,
  };

  public MyCanvas() throws IOException {//构造函数
    super(true);//抑制键盘
    canvasWidth = this.getWidth();
    canvasHeight = this.getHeight();
    try{
    createTank();
    }catch(IOException e){
      System.out.println("error");
    }
    curX = (canvasWidth-mTank.getWidth())/2;
    curY = (canvasHeight-mTank.getHeight())/2;
    mTank.setRefPixelPosition(16,16);
    
  


  }
  
  private void createTank() throws IOException {
    Image image = Image.createImage("/tank.png");
    mTank = new Sprite(image, 32, 32);
  }

  
  public void start() {//开始
    isRun = true;
    Thread t = new Thread(this);//线程
    t.start();//线程开始
  }
  
  public void run() {
    Graphics g = getGraphics();
    
    int timeStep = 80;
    
while (isRun) {

      long start = System.currentTimeMillis();
      tick();
      render(g);
      
      long end = System.currentTimeMillis();
      int duration = (int)(end - start);
      if (duration < timeStep) {
        try { Thread.sleep(timeStep - duration); }
        catch (InterruptedException ie) {}
      }
    }
  }
  
  private void tick() {
    AniCounter+=1;
    mDirection = AniCounter%24;
    mTank.setFrame(kFrameLookup[mDirection/2]);
    mTank.setTransform(kTransformLookup[mDirection/2]);
  }
  
 
  
  private void render(Graphics g) {
    g.setColor(0xffffff);//设置屏幕背景颜色
    g.fillRect(0, 0, canvasWidth, canvasHeight);//用背景颜色填充全屏幕
    mTank.setPosition(curX, curY);
    mTank.paint(g);
    flushGraphics();//闪
    
  }
  
 

  public void stop() {//停止
    isRun = false;
  }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -