代码演示
| package com.arvin;
 import java.awt.image.BufferedImage;
 
 
 
 
 
 public class Enemy implements Runnable {
 
 
 private int x,y;
 
 
 private int type;
 
 
 private boolean face_to = true;
 
 
 private BufferedImage show;
 
 
 private BackGround backGround;
 
 
 private int max_up = 0;
 private int max_down = 0;
 
 
 private Thread thread = new Thread(this);
 
 
 private int image_type = 0;
 
 
 
 
 public Enemy (int x,int y,boolean face_to,int type,BackGround backGround) {
 this.x = x;
 this.y = y;
 this.face_to = face_to;
 this.type = type;
 this.backGround = backGround;
 
 show = StaticValue.Mogu.get(0);
 
 thread.start();
 
 }
 
 
 
 
 public Enemy (int x,int y,boolean face_to,int type,int max_up,int max_down,BackGround backGround){
 this.x = x;
 this.y = y;
 this.face_to = face_to;
 this.type = type;
 this.max_up = max_up;
 this.max_down = max_down;
 this.backGround = backGround;
 
 show = StaticValue.Flower.get(0);
 
 thread.start();
 }
 
 
 
 
 public void death () {
 show = StaticValue.Mogu.get(2);
 this.backGround.getEnemyList().remove(this);
 }
 
 
 
 public int getX() {
 return x;
 }
 
 public int getY() {
 return y;
 }
 
 public BufferedImage getShow() {
 return show;
 }
 
 
 public int getType() {
 return type;
 }
 
 
 @Override
 public void run() {
 while (true){
 
 
 
 if (type == 1) {
 if (face_to){
 this.x -= 2;
 }else{
 this.x += 2;
 }
 
 image_type = image_type == 1 ? 0 : 1;
 show = StaticValue.Mogu.get(image_type);
 }
 
 boolean canLeft = true;
 boolean canRight = true;
 
 
 for (int i = 0; i < backGround.getObstacleList().size(); i++) {
 Obstacle obl = backGround.getObstacleList().get(i);
 
 
 if (obl.getX() == this.x + 36 && (obl.getY() + 65 > this.y && obl.getY() -35 < this.y)) {
 canRight = false;
 }
 
 
 if (obl.getX() == this.x - 36 && (obl.getY() + 65 > this.y && obl.getY() -35 < this.y)) {
 canLeft = false;
 }
 }
 
 
 if (face_to && !canLeft || this.x == 0) {
 face_to = false;
 }else if((!face_to) && (!canRight) || this.x == 764){
 face_to = true;
 }
 
 
 
 
 if (type == 2) {
 if (face_to) {
 this.y -= 2;
 }else{
 this.y += 2;
 }
 image_type = image_type == 1 ? 0 : 1;
 
 if (face_to && (this.y == max_up)) {
 face_to = false;
 }
 
 if ((!face_to) && (this.y == max_down)){
 face_to = true;
 }
 show = StaticValue.Flower.get(image_type);
 }
 try {
 Thread.sleep(50);
 } catch (InterruptedException exception) {
 exception.printStackTrace();
 }
 }
 }
 }
 
 | 
版權聲明: 此文章版權歸Arvin所有,如有轉載,請註明來自原作者