JAVA8怎么实现把有微小偏差坐标分组为相同位置?坐标X和Y都是0.05的偏差就认为多个NPC重叠
[{NPC=强盗, X=0.45, y=0.1}, {NPC=宝箱, X=0.5, y=0.15}
public class Test6 {
//偏移量x
private static final double OFFSET_X = 0.05;
//偏移量y
private static final double OFFSET_Y = 0.05;
public static void main(String[] args) {
NPC npc1=new NPC("海盗",0.45,0.1);
NPC npc2=new NPC("宝箱",0.5,0.15);
if(compareTo(npc1,npc2)){
System.out.println(npc1.getName()+"和"+npc2.getName()+"处在相同的位置");
}else {
System.out.println(npc1.getName()+"和"+npc2.getName()+"处在不同的位置");
}
}
private static boolean compareTo(NPC npc1,NPC npc2){
//精度计算要换成bigDecimal
BigDecimal x1 = BigDecimal.valueOf(npc1.getX());
BigDecimal y1 =BigDecimal.valueOf(npc1.getY());
BigDecimal x2 =BigDecimal.valueOf(npc2.getX());
BigDecimal y2 =BigDecimal.valueOf(npc2.getY());
if (!(Math.abs(x1.subtract(x2).doubleValue())==OFFSET_X)) {
return false;
}
if (!(Math.abs(y1.subtract(y2).doubleValue())==OFFSET_Y)) {
return false;
}
return true;
}
private static class NPC{
private String name;
private double x;
private double y;
public NPC(String name, double x, double y) {
this.name = name;
this.x = x;
this.y = y;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getX() {
return x;
}
public void setX(float x) {
this.x = x;
}
public double getY() {
return y;
}
public void setY(float y) {
this.y = y;
}
}
}