我正在尝试创建一个船的中心位于中间的形状。
one.x
和 one.z
是船的 X 和 Z 位置。船的大小在 X 轴上约为 100,在 Z 轴上约为 50。
Shape my = new Rectangle(
(int) one.x - disToLeft, // upper-left corner X
(int) one.z - disToTop, // upper-left corner Y
disToLeft + disToRight, // width
disToTop + disToBottom // height
);
然后我旋转形状,当然要面向正确的方向。这似乎有效:
int rectWidth = (disToLeft + disToRight);
int rectHeight = (disToTop + disToBottom);
AffineTransform tr = new AffineTransform();
// rotating in central axis
tr.rotate(
Math.toRadians(one.rotation),
x + (disToLeft + disToRight) / 2,
z + (disToTop + disToBottom) / 2
);
my = tr.createTransformedShape(my);
然后我对另一个 Shape 做完全相同的事情,并测试相交。这行得通。
但是,感觉 Shape 的尺寸不正确。或者其他的东西。我的船在很远的一侧(在图形上存在的地方之外)发生碰撞,但在另一侧,我几乎可以在检测到任何碰撞之前直接穿过船!
基本上,形状只是在错误的位置相交。我不知道为什么。形状、位置或旋转一定是错误的。
int disToLeft = 100;
int disToRight = 100;
int disToTop = 150;
int disToBottom = 100;
这些是从中心到左侧、右侧、顶部和底部的距离。
我使用 Z
而不是 Y
因为我的游戏是在 3D 世界中并且海平面几乎相同(因此我不需要担心关于 Y 轴碰撞!)。
更新:
做了很多测试后,我发现矩形的顶部在中间!我做了很多乱七八糟的事情,但由于无法以图形方式看到正方形,因此很难进行测试。
这意味着盒子在船的一侧,像这样:
很明显,当左边的船旋转到这张照片中的样子时,就会检测到碰撞。
最佳答案
看来你的旋转是错误的。以我对数学的理解应该是
tr.rotate(Math.toRadians(one.rotation), x + (disToRight - disToLeft) /2, z + (disToBottom - disToTop) /2);
注意变量的符号和顺序
编辑:
让我们拆开公式:
你的 Rectangle 是这样定义的:
x-coordinate (x): one.x-disToLeft
y-coordinate (y): one.z-disToTop
width: disToLeft+disToRight
height: disToTop+disToBottom
因此,矩形的中心(旋转的位置)是:
(x+width/2)
(y+height/2)
如果用上面的声明替换 x、width、y 和 height
(one.x-disToLeft + (disToLeft+disToRight)/2)
(one.z-disToTop + (disToTop+disToBottom)/2)
这已经是您需要的点,但可以简单化:
one.x- disToLeft + (disToLeft+disToRight)/2
is equal to
one.x-(2*disToLeft/2)+(disToLeft/2)+(disToRight/2)
is equal to
one.x-(distoLeft/2) + (disToRight/2)
is equal to
one.x+(disToRight-disToLeft)/2
另一个坐标完全一样。
关于java - 两个 Shape 对象似乎在错误的位置相交?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29463045/