如果作为参数传入的Sprite的任何部分与当前Sprite重叠,我需要使重叠函数返回true。我想过使用矩形,但我正在寻找更简单的东西。
abstract class Sprite
{
private int x;
private int y;
private int size;
private int w;
private int h;
private int xSlope;
private int ySlope;
private Image image;
private static Random rand;
public Sprite(int xIn, int yIn, int width, int height, String imagePath, int imageSize) {
if (rand == null) {
rand = new Random();
}
size = imageSize;
setImage(imagePath);
x = xIn;
y = yIn;
w = width;
h = height;
xSlope = rand.nextInt(11) - 5;
ySlope = rand.nextInt(11) - 5;
}
public int getX() { return x; }
public int getY() { return y; }
public int getSize() { return size; }
public void setSize(int s) { size = s; }
public void setX(int xIn) { x = xIn; }
public void setY(int yIn) { y = yIn; }
public void setImage(String imagePath) {
try {
image = ImageIO.read(new File(imagePath));
} catch (IOException ioe) {
System.out.println("Unable to load image file.");
}
}
public Image getImage() { return image; }
public boolean overlaps(Sprite s) {
}
public void update(Graphics g) {
g.drawImage(getImage(), x, y, getSize(), getSize(), null);
}
public void move() {
// Move the Sprite
int x = getX() + xSlope;
int y = getY() + ySlope;
if (x < 0) x = w;
if (x > w) x = 0;
if (y < 0) y = h;
if (y > h) y = 0;
setX(x);
setY(y);
}
}
答案 0 :(得分:1)
我假设一个Sprite
代表一个矩形,并且所讨论的Sprites
都是AABB&#(轴对齐的边界框...一个边缘与其平行的矩形坐标平面)。如果这是真的,你可以检查他们的位置和他们的大小。
(以下假设正Y表示向下方向)
public boolean overlaps(Sprite s)
{
return
(
(this.getX() < s.getX()+s.getWidth()) && // check right side overlap
(this.getX()+this.getWidth() > s.getX()) && // check left side overlap
(this.getY() < s.getY()+s.getHeight()) && // check bottom side overlap
(this.getY()+this.getHeight() > s.getY()) // check top side overlap
);
}
此代码使用分离轴定理(SAT)。这背后的基本思想是你假设所有方面已经重叠。一旦找到不重叠的单面,这意味着矩形不会重叠,因此您可以返回。您可以通过Metanet软件在this fantastic tutorial中阅读有关SAT(以及2D空间中的其他碰撞检测方法)的更多信息。
答案 1 :(得分:-2)