Javascript 我怎样才能始终以相同的速度将球移动到(x,y)位置,而不考虑其起始位置

Javascript 我怎样才能始终以相同的速度将球移动到(x,y)位置,而不考虑其起始位置,javascript,jquery,game-physics,Javascript,Jquery,Game Physics,这张图片很好地说明了我的问题: 当球靠近其端点(橙色圆圈)时移动非常慢,但当球远离其端点时移动非常快 发生这种情况的原因是因为我使用这个代码来计算球的垂直和水平速度 var startingBallSpeed = 100; xDistance = targetX - this.x; yDistance = targetY - this.y; this.horizontalVelocity = (xDistance / startingBallSpeed); this.verticalVelo

这张图片很好地说明了我的问题:

当球靠近其端点(橙色圆圈)时移动非常慢,但当球远离其端点时移动非常快

发生这种情况的原因是因为我使用这个代码来计算球的垂直和水平速度

var startingBallSpeed = 100;
xDistance = targetX - this.x;
yDistance = targetY - this.y;

this.horizontalVelocity = (xDistance / startingBallSpeed);
this.verticalVelocity = (yDistance / startingBallSpeed);
问题:我如何确保球以相同的速度移动,并且仍然会击中targetX和targetY

当前行为:靠近端点的球移动缓慢,远离端点的球移动快速
期望的行为:球以相同的速度移动,无论它们离终点有多近

JS:


您需要规范化由xDistance、ydDistance定义的向量,以创建一个单位向量,该单位向量指定方向,但长度为1。然后你可以把它乘以你想要的球速度,得到速度

通过除以长度进行规格化:

xDistance = targetX - this.x;
yDistance = targetY - this.y;
length = Math.sqrt((xDistance * xDistance) + (yDistance * yDistance));
if(length > 0) // avoid divide by zero
{
     xUnitVector = xDistance / length;
     yUnitVector = yDistance / length;

     this.horizontalVelocity = xUnitVector * startingBallSpeed;
     this.verticalVelocity = yUnitVector * startingBallSpeed;
}
else
{
     // cancel the launch because you are already at your destination
}

将球的速度调整为所需的恒定速度

您需要规范化由xDistance、ydDistance定义的向量,以创建指定方向但长度为1的单位向量。然后你可以把它乘以你想要的球速度,得到速度

通过除以长度进行规格化:

xDistance = targetX - this.x;
yDistance = targetY - this.y;
length = Math.sqrt((xDistance * xDistance) + (yDistance * yDistance));
if(length > 0) // avoid divide by zero
{
     xUnitVector = xDistance / length;
     yUnitVector = yDistance / length;

     this.horizontalVelocity = xUnitVector * startingBallSpeed;
     this.verticalVelocity = yUnitVector * startingBallSpeed;
}
else
{
     // cancel the launch because you are already at your destination
}

将球的速度调整到您需要的恒定速度

这太完美了!非常感谢。真不敢相信我这么快就得到了答案。我知道我需要把它除以一些东西,但我从来没有想过用a^2+b^2=c^2。我用x距离和y距离除以,这太完美了!非常感谢。真不敢相信我这么快就得到了答案。我知道我需要把它除以一些东西,但我从来没有想过用a^2+b^2=c^2。而是除以x距离和y距离