我采用的代码受this answer的启发很大,但我的弹丸未按我期望的方式归位。初始弹丸方向通常垂直于目标。在这一点上,它似乎确实指向他的方向,但是,如果它“通过”他,它似乎像被冻结在某个点上一样被卡在适当的位置,但随后似乎遵循了目标所做的动作而没有移动其预期的目标速度。我已经评论了我关注的代码行。他在算法中使用的是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

最佳答案

根据我的说法,如果您有一个向量(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逆时,角度弧度可能有多个可能性。您可能必须检查两个向量所处的象限。您在任一方向上的最大转弯速度均为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)

07-24 09:49
查看更多