gpt4 book ai didi

java - 获取双速度 vector 以正确计算而无需舍入

转载 作者:行者123 更新时间:2023-11-30 07:38:52 27 4
gpt4 key购买 nike

我目前正在编写一个简单的游戏,其中有许多城镇,其中有一定数量的士兵,并且每秒都会增加。一个玩家拥有的城镇可以攻击另一个玩家拥有的城镇,导致原来城镇的士兵数量分成两半,另一半去攻击另一个城镇。

问题是我将攻击士兵表示为朝向另一个城镇的形状,并且我使用碰撞检测来确定攻击何时到达。因此,攻击用于到达城镇的 vector 必须正确,这样才能真正到达城镇,这一点很重要。

每个城镇都有一个名为 attackPointPoint 字段,我将其用作攻击的起点以及攻击的目的地。 attackPoint 位于碰撞场的中间。

这是我初始化攻击并创建运动 vector 的代码:

public Attack(int troops, Team owner, Town source, Town destination) {
this.troops = troops; //troops included in the attack
this.owner = owner; //player that who sent the attack
this.destination = destination; //town the attack is going towards

Point srcPoint = source.getAttackPoint(); //attackPoint of the source
Point destPoint = destination.getAttackPoint(); //attackPoint of the destination town

x = srcPoint.x; //int --- the attack originates at the src's attack point
y = srcPoint.y; //int

double hypotenuse = Math.sqrt(Math.pow(destPoint.y - y, 2) + Math.pow(destPoint.x - x, 2));
double adjacent = destPoint.x - x;
double opposite = destPoint.y - y;
xVelocity = 3.0 * (adjacent / hypotenuse); //field, double
yVelocity = 3.0 * (opposite / hypotenuse);
}

然后另一种方法实际上移动了攻击 -

public void move() {
x += xVelocity;
y += yVelocity;
}

我可以通过测试确认 getAttackPoint() 返回的 attackPoints 都是正确的,并且我进行碰撞检测的方式工作正常。这里的问题是,似乎我的速度变量或其他一些变量正在四舍五入,因此攻击只能采用一些预定义的路径。例如:

//trying to attack X2     //trying to attack X1
X............... X------------------
.\.............. .........X1.....
..\............. ................
...\............ ................
....\........... ................
.....X1..X2..... ................

“预定义”路径似乎每隔 30 度左右,我可以直接向上、向下、向左和向右发送攻击,这就是为什么我认为会出现一些舍入误差当我计算 vector 并进行三角函数时。当我有两个靠近的城镇时,无论我尝试攻击哪一个,两个攻击都会遵循相同的路径(图 1)。另外,当我有一个城镇靠近源城镇东/西 180 度时,我发送的攻击将直接向东/西移动(图 2)。

如果有人能发现问题,或者给我一个关于如何让对象从一个点或另一个点沿直接路径行进的建议,我将不胜感激!

最佳答案

虽然我确实检查了你计算二维加速度的方法,但它看起来很奇怪。

您需要由两点(源点和目标点)定义的直线的斜率。

double slope = (destination.y - source.y)/(destination.x - source.x);
xVelocity = 1; // do the normalisation as you wish
yVelocity = xVelocity * slope;

一般来说,我建议您使用 vector 而不是 x 和 y 变量。您可以概括大多数操作,并使代码更具可读性和无重复性(在这种情况下,连接源和目标的线段将是由目标 - 源给出的 vector )。

关于java - 获取双速度 vector 以正确计算而无需舍入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34971277/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com