MyCanvas.java
资源名称:J2ME&Game.rar [点击查看]
上传用户:gyyuli
上传日期:2013-07-09
资源大小:3050k
文件大小:3k
源码类别:
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;
- }
- }