我正在用java制作一个游戏,我已经完成了大部分工作。然而,我需要修复的最后一个错误之一就是敌人的精灵可以相互重叠并在屏幕上相互叠加。我想这样做,如果敌人的精灵碰撞他们只能触摸但不能重叠。这是敌人类的代码。
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Rectangle;
import java.util.ArrayList;
import javax.swing.ImageIcon;
public class Enemy extends Base {
int x;
int y;
int velx = -2;
int vely = 0;
public Enemy(int x, int y) {
super(x,y);
this.x = x;
this.y = y;
}
public void update() {
movement();
x += velx;
y += vely;
if (x < - 15) {
x = -15;
movement();
}
if (x > 1100) {
x = 1100;
movement();
}
if (y > 660) {
y = 660;
movement();
}
if (y < 10) {
y = 10;
movement();
}
}
public void draw(Graphics g) {
g.drawImage(getEnemyImage(), x, y, null);
}
public static Image getEnemyImage(){
ImageIcon ic = new ImageIcon("enemy.gif");
return ic.getImage();
}
public Rectangle getBounds(){
return new Rectangle(x, y, getEnemyImage().getWidth(null), getEnemyImage().getHeight(null));
}
public void checkColision(){
ArrayList<Base> enemies = GamePanel.getEnemyList();
if (x <= 0) {
velx = 2;
}
if (x >= 1096) {
velx = -2;
}
for (int a = 0; a < enemies.size(); a++) {
Base temp = GamePanel.enemy.get(a);
if (getBounds().intersects(temp.getBounds())) {
// where the collision check should happen.
}
}
}
public void movement(){
if (y > 16) {
if (x > GamePanel.p.getX()) {
velx = - 2;
}
if (x < GamePanel.p.getX()) {
velx = 2;
}
if (y > GamePanel.p.getY()) {
vely = -2;
}
if (y < GamePanel.p.getY()) {
vely = 2;
}
}
}
}
这就是产生敌人的地方。
for (int a = 0; a < enemy_amount; a++) {
space += 50;
int rand = (int)(Math.random() * 2) + 1;
if (rand == 1) {
int randp = (int)(Math.random() * 2) + 1;
int x = 0;
int y = 0;
if (randp == 1) {
x = 1250 + space;
y = 500;
}
if (randp == 2) {
x = 1250 + space;
y = 100;
}
enemy.add(new Enemy(x,y));
}
if (rand == 2) {
int randp = (int)(Math.random() * 2) + 1;
int x = 0;
int y = 0;
if (randp == 1) {
x = 250;
y = -100 - space;
}
if (randp == 2) {
x = 850;
y = -100 - space;
}
enemy.add(new Enemy2(x,y));
}
}
任何帮助都会很棒,因为我真的被卡住了。