所以我有一个划船游戏,其中船对象必须使用箭头键躲避随机放置的障碍物。如果船撞到其中一个障碍物,船会受到随机数量的伤害。船是一张 27x52 的图片(两边各有 2 个像素,所以代码显示为 2-25),障碍物是矩形。
我大部分时间都在进行命中检测。但是,只要船位于比宽度高的矩形的右侧,即使船距离矩形的右边缘大约 5-10 像素,它也会受到损坏。请参阅此图像以更好地理解该问题:http: //imgur.com/pqDLMrl
在我的代码中,我创建了一个包含 15 个障碍物的数组。障碍采用参数(颜色颜色、int damageDealt、int xPos、int yPos、int width、int height、boolean hasHit)。
//Create array of obstacles
for(int x = 0; x < 15; x++) {
obstacles[x] = new Obstacle((new Color(rand.nextInt(81), rand.nextInt(51), rand.nextInt(51))), rand.nextInt(21) + 10, rand.nextInt(601),
(-x * (rand.nextInt(51) + 31)), (rand.nextInt(31) + 5), (rand.nextInt(31) + 5), false);
}
这是命中检测代码(这是在一个循环遍历障碍物对象数组的循环中:
for(int y = 2; y <= 25; y++) {
//Obstacles hit detection
for(int z = 0; z <= obstacles[x].getw(); z++) {
if(boat.getx() + y == obstacles[x].getx() + z && boat.gety() == obstacles[x].gety()) {
if(!obstacles[x].getDamaged()) {
boat.setHealth(boat.getHealth() - obstacles[x].getdmg());
obstacles[x].setDamaged(true);
}
}
}
现在它在船的 x 值中循环,从 2 到 25,而不是 0 到 27,因为两边都没有两个像素。然后循环遍历障碍物的 x 值(xPos 到 xPos+width)并查看这些值是否匹配。如果匹配,并且 y 值匹配,则船将受到损坏。请记住,这只发生在船位于障碍物的右侧并且障碍物的高度大于宽度的情况下。我没有看到我的代码有问题,但我无法找到解决我的错误的方法。谢谢。
编辑:这是船和障碍物类的代码。
import java.awt.Color;
import java.awt.Rectangle;
public class Obstacle {
private int dmg, xPos, yPos, height, width;
private Color color;
private boolean hasDamaged;
public Obstacle(Color hue, int damage, int x, int y, int w, int h, boolean damaged) {
dmg = damage;
xPos = x;
yPos = y;
width = w;
height = h;
color = hue;
hasDamaged = damaged;
}
public boolean getDamaged() {
return hasDamaged;
}
public void setDamaged(boolean damaged) {
hasDamaged = damaged;
}
public Color getColor() {
return color;
}
public int getdmg() {
return dmg;
}
public void setdmg(int damage) {
dmg = damage;
}
public int getx() {
return xPos;
}
public void setx(int x) {
xPos = x;
}
public int gety() {
return yPos;
}
public void sety(int y) {
yPos = y;
}
public int getw() {
return width;
}
public void setw(int w) {
width = w;
}
public int geth() {
return height;
}
public void seth(int h) {
height = h;
}
public Rectangle getBounds() {
return new Rectangle(xPos, yPos, width, height);
}
}
和船类:
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.awt.Rectangle;
public class Boat {
private int hp, xPos, yPos, dx;
private BufferedImage boatPic;
public Boat(BufferedImage img, int health, int x, int y, int velX) {
boatPic = img;
hp = health;
xPos = x;
yPos = y;
dx = velX;
}
public BufferedImage getImage() {
return boatPic;
}
public void setImage(BufferedImage img) {
boatPic = img;
}
public int getHealth() {
return hp;
}
public void setHealth(int health) {
hp = health;
}
public int getx() {
return xPos;
}
public void setx(int x) {
xPos = x;
}
public int gety() {
return yPos;
}
public void sety(int y) {
yPos = y;
}
public int getdx() {
return dx;
}
public void setdx(int velX) {
dx = velX;
}
public Rectangle getBounds() {
return new Rectangle(xPos, yPos, 25, 49);
}
}