我一年多前开始学习java,所以我还是很新。
无论第二个点在框架中的哪个位置,我都试图让一个对象以恒定的净速度从一个点移动到另一个点。目前,只要我每隔几帧运行一次该方法,它就可以很好地工作。
唯一的问题是它只会水平移动,除非第二个点大约在 45 到 135 度或 225 到 315 度之间(1/2π 和 3/2π 或 5/2π 和 7/2π)。
这可能是因为“if”语句旨在阻止它除以 0,但它看起来不像。此外,如果有任何方法可以简化这些方程式或删除“if”语句,我也不介意那里有一些建议。
注意:vel 是物体行进的净速度,Prime.mx 和 Prime.my 是目标点的位置。
public void target()
{
if (Prime.mx > x)
{
if (Math.abs(x-Prime.mx) != 0)
x = Math.round(Math.round((x + (vel*Math.cos(Math.atan(Math.abs(y-Prime.my)/Math.abs(x-Prime.mx)))))));
}
if (Prime.mx < x)
{
if (Math.abs(x-Prime.mx) != 0)
x = Math.round(Math.round((x - (vel*Math.cos(Math.atan(Math.abs(y-Prime.my)/Math.abs(x-Prime.mx)))))));
}
if (Prime.my > y)
{
if (Math.abs(x-Prime.mx) != 0)
y = Math.round(Math.round((y + (vel*Math.sin(Math.atan(Math.abs(y-Prime.my)/Math.abs(x-Prime.mx)))))));
}
if (Prime.my < y)
{
if (Math.abs(x-Prime.mx) != 0)
y = Math.round(Math.round((y - (vel*Math.sin(Math.atan(Math.abs(y-Prime.my)/Math.abs(x-Prime.mx)))))));
}
}
我使用 Math.round 两次,因为第一次将它从 double 带到 float,第二次将其变成 int。我需要 x 和 y 作为整数,以便绘制方法可以绘制对象。
我在网站上发现了一些类似的问题,但最接近的问题是在 python 中,并且答案似乎不适用于我的问题。