移动图片的转换:
定义一个方向,在移动的时候判断下一次移动是否为当前方向,如果不是则只改变图片,不做移动。
1 package com.itheima.bean; 2 3 public class Tank extends Element { 4 private int speed = 64; 5 Direction direction = Direction.UP; //初始向上 6 7 public Tank(int x, int y) { 8 this.x = x; 9 this.y = y; 10 this.imagePath = "res/img/tank_u.gif"; 11 12 } 13 14 public void move(Direction dir) { 15 if (direction != dir) { //如果传进来的方向不等于当前方向 16 direction = dir; 17 switch (dir) { //根据方向转换图片 18 case UP: 19 this.imagePath = "res/img/tank_u.gif"; 20 break; 21 22 case DOWN: 23 this.imagePath = "res/img/tank_d.gif"; 24 break; 25 case LEFT: 26 this.imagePath = "res/img/tank_l.gif"; 27 break; 28 case RIGHT: 29 this.imagePath = "res/img/tank_r.gif"; 30 break; 31 } 32 return ; //不继续向下执行 33 } 34 switch (dir) { //移动 35 case UP: 36 y -= speed; 37 break; 38 39 case DOWN: 40 y += speed; 41 break; 42 case LEFT: 43 x -= speed; 44 break; 45 case RIGHT: 46 x += speed; 47 break; 48 } 49 } 50 }
随笔说:
游戏移动原理就是图片的坐标的变化显示。
时间: 2024-10-13 11:13:52