实现动画
1.实现循环播放动画类TimerTask
//声明标记
int flag = 1;
class HeroAnimation extends TimerTask {
@Override
public void run() {
if (flag == 1) {
flag = 2;
} else {
flag = 1;
}
Hero.this.image = ImageLoaderUtil.load(“hero” + flag + “.png”);
}
}
2.调用
//执行飞行动画
Timer timer = new Timer();
timer.schedule(new HeroAnimation(),0, 200);
实现移动
1.编写ActionSprite 接口
public interface ActionSprite {
default void down(){
System.out.println(“向下运动”);
}
default void up(){
System.out.println(“向下运动”);
}
default void move(int code){
System.out.println(“向下运动”);
}
}
2.Hero 类实现ActionSprite 编写飞机移动方法
@Override
public void move(int code) {
switch (code) {
case KeyEvent.VK_LEFT:
int x = this.x - 5;
if (x < 0) {
x = 0;
}
//左
this.x = x;
break;
case KeyEvent.VK_UP:
int y = this.y - 5;
if (y < 0) {
y = 0;
}
//上
this.y = y;
break;
case KeyEvent.VK_RIGHT:
//右移动
x = this.x + 5;
if (x > (400 - this.width - 16)) {
x = 400 - this.width - 16;
}
this.x=x;
break;
case KeyEvent.VK_DOWN:
//下移动
y = this.y + 5;
if (y > (600 -this.height - 30)) {
y = 600 - this.height - 30;
}
this.y=y;
break;
}
}
4.监听键盘按下事件
this.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
//获取被按下的按键码
int code = e.getKeyCode();
hero.move(code);
}
});