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

📄 playertanksprite.java

📁 tank游戏
💻 JAVA
字号:
package src;

import java.io.IOException;

import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.game.Sprite;

public class PlayerTankSprite extends Sprite {
	private int frameWidth;

	private int frameHeight;

	private int backspeed;

	private int orientation;

	public BulletsSprite bullets;

	private static final int[] kTransformLookup = { Sprite.TRANS_MIRROR_ROT270,
			Sprite.TRANS_MIRROR_ROT270, Sprite.TRANS_ROT90, Sprite.TRANS_NONE,
			Sprite.TRANS_ROT180 };// 定义旋转方式,只能用到后面四个,编号为1,2,3,4对应图片左右上下。

	public PlayerTankSprite(Image image, int frameWidth, int frameHeight) {
		super(image, frameWidth, frameHeight);
		this.frameWidth = frameWidth;
		this.frameHeight = frameHeight;
		defineReferencePixel(frameWidth / 2, frameHeight / 2);// 定位旋转点
		try {
			bullets = createBullets();

			bullets.setVisible(false);
			TankCanvas.tankLayermanager.append(bullets);
		} catch (Exception e) {
		}
	}

	public BulletsSprite createBullets() throws IOException {
		Image image = Image.createImage("/res/bullets.png");
		return new BulletsSprite(image, 3, 3);
	}

	public void forward(int speed, int direction) {// speed为速度,direction为方向
		if (direction == 1) {// 为1时方向为左
			tankMove(speed, 0);
		} else if (direction == 2) {// 为2时方向为右
			tankMove(speed, 0);
		} else if (direction == 3) {// 为3时方向为上
			tankMove(0, speed);
		} else if (direction == 4) {// 为4时方向为下
			tankMove(0, speed);
		}

		setTransform(kTransformLookup[direction]);// 根据运动方向设置图片显示的样式
		orientation = direction;// orientation为碰撞后的方向保持

		backspeed = -speed;// backspeed为碰撞后返回点的定位。

	}

	public void undo() {
		forward(backspeed, orientation);
	}

	private void tankMove(int kx, int ky) {// 坦克精灵移动偏移量(kx,ky)定位精灵的x,y坐标值设定
		int x = getX();// 精灵当前的x坐标
		int y = getY();// 精灵当前的y坐标
		x += kx;
		y += ky;
		// 下面的条件判断为出边界的设定,这里手机屏幕大小为定值(180,177),不是太合理。
		if (x < 0 || x > 180 - this.frameWidth) {
			x -= kx;
		}
		if (y < 0 || y > 177 - this.frameHeight) {
			y -= ky;
		}
		setPosition(x, y);// 坦克精灵的移动方法实现
		// System.out.print("now position:"+x+","+y);
	}
}

⌨️ 快捷键说明

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