1

我采用了深受这个答案启发的代码,但我的弹丸没有按照我期望的方式归位。初始弹丸方向通常垂直于目标。在这一点上,它似乎确实在他的方向上,但如果它“通过”他,它似乎会卡在原地,就像它在某个点上被冻结一样,但随后似乎会跟随目标的动作而没有按预期移动速度。我已经注释了一行我担心的代码。他在他的算法中使用了 V3 和 V4,我怀疑这是他的错字,但我不确定。如果有人可以帮助我解决我在这里做错的事情,我将不胜感激。

normalizedDirectionToTarget = root.vector.normalize(target.pos.x - attack.x, target.pos.y - attack.y) #V4
V3 = root.vector.normalize(attack.velocity.x, attack.velocity.y)
normalizedVelocity = root.vector.normalize(attack.velocity.x, attack.velocity.y)

angleInRadians = Math.acos(normalizedDirectionToTarget.x * V3.x + normalizedDirectionToTarget.y * V3.y)
maximumTurnRate = 50 #in degrees
maximumTurnRateRadians = maximumTurnRate * (Math.PI / 180)
signOfAngle = if angleInRadians >= 0 then 1 else (-1)
angleInRadians = signOfAngle * _.min([Math.abs(angleInRadians), maximumTurnRateRadians])
speed = 3
attack.velocity = root.vector.normalize(normalizedDirectionToTarget.x + Math.sin(angleInRadians), normalizedDirectionToTarget.y + Math.cos(angleInRadians)) #I'm very concerned this is the source of my bug
attack.velocity.x = attack.velocity.x * speed
attack.velocity.y = attack.velocity.y * speed
attack.x = attack.x + attack.velocity.x
attack.y = attack.y + attack.velocity.y

编辑:有效的代码

normalizedDirectionToTarget = root.vector.normalize(target.pos.x - attack.x, target.pos.y - attack.y) #V4
normalizedVelocity = root.vector.normalize(attack.velocity.x, attack.velocity.y)
angleInRadians = Math.acos(normalizedDirectionToTarget.x * normalizedVelocity.x + normalizedDirectionToTarget.y * normalizedVelocity.y)
maximumTurnRate = .3 #in degrees
maximumTurnRateRadians = maximumTurnRate * (Math.PI / 180)
crossProduct = normalizedDirectionToTarget.x * normalizedVelocity.y - normalizedDirectionToTarget.y * normalizedVelocity.x
signOfAngle = if crossProduct >= 0 then -1 else 1
angleInRadians = signOfAngle * _.min([angleInRadians, maximumTurnRateRadians])
speed = 1.5
xPrime = attack.velocity.x * Math.cos(angleInRadians) - attack.velocity.y * Math.sin(angleInRadians)
yPrime = attack.velocity.x * Math.sin(angleInRadians) + attack.velocity.y * Math.cos(angleInRadians)
attack.velocity = root.vector.normalize(xPrime, yPrime)
attack.velocity.x *= speed
attack.velocity.y *= speed
attack.x = attack.x + attack.velocity.x
attack.y = attack.y + attack.velocity.y
4

1 回答 1

1

根据我的说法,如果你有一个向量 (x,y) 并且你想将它围绕原点旋转角度“theta”,那么新向量 (x1,y1) 将变为:

x1 = x*cos(theta) - y*sin(theta)

y1 = y*cos(theta) + x*sin(theta)

(以上可以用极坐标推导出来)

编辑:我不确定我是否理解正确,但是如果您知道最终角度的速度和绝对值(例如 phi),那么您为什么不能简单地做:

Vx = 速度*cos( phi )

Vy = 速度*sin( phi )

编辑 2:此外,在取 cos-inverse 时,角度弧度可能有多种可能性。您可能必须检查两个向量所在的象限。您的最大转弯率在任一方向均为 50 度。因此,该角度的余弦应始终为正。(余弦仅在 90 到 270 度时为负。

编辑 3:我认为要获取有关 +ve 转向或 -ve 转向的信息,叉积是一个更好的主意。

编辑 4:如果您执行以下操作,Vx / Vy 应该可以工作:

initialAngleInRadians = Math.atan(normalizedVelocity.y / normalizedVelocity.x)
finalAngleInRadians = initialAngleInRadians + angleInRadians
Vx = speed*cos(finalAngleInRadians)
Vy = speed*sin(finalAngleInRadians)
于 2013-09-11T06:01:08.010 回答