我一直在为我正在研究的模拟创建一个六边形(平顶)网格。我试图从指定的目标六边形算出六边形之间的距离。
我的解决方案大部分时间都有效,除了目标以北目标六边形的每个奇数列都向上移动 1。我知道这听起来令人困惑,但我附上了一张图片来解释我的意思:
正如你们所看到的,目标六边形下方网格的下半部分和目标六边形上方的所有其他列都是正确的。我不明白为什么:S
这是对轴向和立方体坐标的解释。
http://www.redblobgames.com/grids/hexagons/#coordinates
这是负责将轴向坐标转换为立方体坐标的代码。
public void setQR(int theQ, int theR){
this.q = theQ;
this.r = theR;
this.x = this.q;
this.z = this.r - (this.q - (this.q&1)) /2;
this.y = -(this.x + this.z);
}
这是计算距离的代码。
仅供参考,六边形是从中心点(CPx,CPy)创建的。
private double distance = 0;
public double workOutDistance(Hexagon hexagon, HexagonFood target){
double targetX = target.getCPX();
double targetY = target.getCPY();
double hexagonX = hexagon.getCPX();
double hexagonY = hexagon.getCPY();
double deltaX = (targetX-hexagonX)*-1;
double deltaY = (targetY-hexagonY)*-1;
double deltaXRadius = (deltaX/(SimField.hexSize)/1.5);
double deltaYApothem = (deltaY/(SimField.hexSize/1.155)/2);
hexagon.setQR((int)deltaXRadius, (int)deltaYApothem);
ArrayList<Integer> coords = new ArrayList<>();
coords.add(
Math.abs(hexagon.getX() - target.getX())
);
coords.add(
Math.abs(hexagon.getZ() - target.getZ())
);
coords.add(
Math.abs(hexagon.getY() - target.getY())
);
System.out.println(coords);
distance = Collections.max(coords);
return distance;
}
谁能告诉我为什么会这样?将不胜感激。
编辑:
按照 Tim 的建议将 Int 更改为 Double 后,我明白了。
http://i.stack.imgur.com/javZb.png
**
解决方案
**
在尝试了给出的答案之后,这个小调整解决了这个问题。
改变这个..
public void setQR(int theQ, int theR){
this.q = theQ;
this.r = theR;
this.x = this.q;
this.z = this.r - (this.q - (this.q&1)) /2;
this.y = -(this.x + this.z);
}
到这个..
public void setQR(int theQ, int theR){
this.q = theQ;
this.r = theR;
this.x = this.q;
if (this.r>0){
this.z = this.r - (this.q - (this.q&1))/2;
}
else {
this.z = this.r - (this.q + (this.q&1))/2;
}
this.y = -(this.x + this.z);
}