虽然应该不是最优的,但是是逻辑较简单的那种
逻辑是:检查物体的4个点是否有至少一个在另外一个物体里,有就相撞了。
//冲撞检测
public boolean collidesWith(Layer otherSprite) {
if (otherSprite == null) {
throw new NullPointerException();
}
// 可见物体才需要相撞
if (otherSprite.isVisible() && this.isVisible()){
float otherX = otherSprite.getX();
float otherY = otherSprite.getY();
float otherWidth = otherSprite.getWidth();
float otherHeight = otherSprite.getHeight();
float thisX = getX();
float thisY = getY();
float thisWidth = getWidth();
float thisHeight = getHeight();
//判断this物体的4个顶点坐标是否在Other里面,就为碰撞
boolean f1 = (thisX + thisWidth) > otherX && (thisX + thisWidth) < (otherX + otherWidth) && (thisY + thisHeight) > otherY && (thisY + thisHeight) < (otherY + otherHeight) ;
boolean f2 = thisX > otherX && thisX < (otherX + otherWidth) && (thisY + thisHeight) > otherY && (thisY + thisHeight) < (otherY + otherHeight);
boolean f3 = (thisX + thisWidth) > otherX && (thisX + thisWidth) < (otherX + otherWidth) && thisY > otherY && thisY < (otherY + otherHeight);
boolean f4 = thisX > otherX && thisX < (otherX + otherWidth) && thisY > otherY && thisY < (otherY + otherHeight);
if(f1||f2||f3||f4){
return true;
}
}
return false;
}