package
com.mocn.framework;
import
java.util.Hashtable;
import
android.graphics.Bitmap;
import
android.graphics.Canvas;
import
android.graphics.Paint;
/**
* 精灵组件类,添加精灵组件,设置动作,绘制精灵,添加一个动作序列,精灵动作类
* @author Administrator
*/
public
class
Sprite
extends
Layer {
public
int
frameIdx;
// 当前帧下标
public
int
currentFrame =
0
;
// 当前帧
public
Hashtable<String, SpriteAction> actions;
// 动作集合
public
SpriteAction currentAction;
// 当前动作
public
Sprite(Bitmap bitmap,
int
w,
int
h,
boolean
autoAdd) {
super
(bitmap, w, h, autoAdd);
actions =
new
Hashtable<String, Sprite.SpriteAction>();
// 用Hashtable保存动作集合
/**
* 设置动作的方法
* @param actionName
*/
public
void
setAction(String actionName) {
currentAction = actions.get(actionName);
// 从动作集合中得到该动作
/**
* 绘制精灵的方法
*/
@Override
public
void
drawSelf(Canvas canvas, Paint paint) {
if
(currentAction !=
null
) {
currentFrame = currentAction.frames[frameIdx];
// 获取当前需要的帧
// 截取图片中需要的帧
src.left = currentFrame * w;
// 左端宽度:当前帧乘上帧的宽度
src.top =
0
;
// 上端高度:0
src.right = src.left + w;
// 右端宽度:左端宽度加上帧的宽度
src.bottom = h;
// 下端高度为帧的高度
// 绘制在界面上,取中心点绘制
dst.left = (
int
) x - w /
2
;
dst.top = (
int
) y - h /
2
;
dst.right = dst.left + w;
dst.bottom = dst.top + h;
canvas.drawBitmap(bitmap, src, dst, paint);
// 绘制当前帧
if
(currentAction !=
null
) {
currentAction.nextFrame();
// 绘制下一帧
/**
* 添加一个动作集合的方法
* @param name
* @param frames
* @param frameTime
*/
public
void
addAction(String name,
int
[] frames,
int
[] frameTime) {
SpriteAction sp =
new
SpriteAction();
// 创建SpiteAction的对象
sp.frames = frames;
// 当前帧的数量,用下标表示
sp.frameTime = frameTime;
// 每一帧切换的时间
actions.put(name, sp);
// 将名字为"name"的动作集合,值为sp的动作集合放进acitons中
/**
* 精灵的移动方法
* @param dx
* @param dy
*/
public
void
move(
int
dx,
int
dy) {
this
.x += dx;
this
.y += dy;
// 精灵动作类
class
SpriteAction {
public
int
[] frames;
// 该动作的帧序列
public
int
[] frameTime;
// 帧序列中每一帧切换对应的时间
private
long
updateTime;
// 记录上次失效时间
/**
* 切换到下一帧的方法
*/
public
void
nextFrame() {
if
(System.currentTimeMillis() > updateTime) {
frameIdx++;
// 帧下标增加
frameIdx %= frames.length;
updateTime = System.currentTimeMillis() + frameTime[frameIdx];
// 切换下一帧所需要的时间
- 海报