更新时间:2022-04-25 09:30:15
希望我没有弄错 - 我不太记得了.
I hope I didn't make mistake - I don't remeber it too well.
atan2(dy, dx)
有错误 - 必须是 atan2(dx, dy)
there was mistake in atan2(dy, dx)
- has to be atan2(dx, dy)
如果你有子弹的位置和速度,以及目标的位置,它会计算新的位置(一帧/移动后)位置.
It calculate new position (after one frame/move) if you have bullet's position and speed, and target's position.
你必须重复一遍
import math
speed = 10
# bullet current position
x1 = 0
y1 = 0
# taget possition
x2 = 100
y2 = 100
dx = x2 - x1
dy = y2 - y1
angle = math.atan2(dx, dy)
#print(math.degrees(angle))
cx = speed * math.sin(angle)
cy = speed * math.cos(angle)
#print(cx, cy)
# bullet new current position
x1 += cx
y1 += cy
print(x1, y1)
循环示例
它需要 abs()
在 if abs(cx)
顺便说一句:如果 target
没有改变位置或者 bullet
没有改变 angle
那么你可以只计算一次 cx,cy
.
BTW: if target
doesn't change place or bullet
doesn't change angle
then you can calculate cx,cy
only once.
import math
def move(x1, y1, x2, y2, speed):
# distance
dx = x2 - x1
dy = y2 - y1
# angle
angle = math.atan2(dx, dy)
#print(math.degrees(angle))
#
cx = speed * math.sin(angle)
cy = speed * math.cos(angle)
#print(cx, cy)
# if distance is smaller then `cx/cy`
# then you have to stop in target.
if abs(cx) < abs(dx) or abs(cy) < abs(dy):
# move bullet to new position
x1 += cx
y1 += cy
in_target = False
else:
# move bullet to target
x1 = x2
y1 = y2
in_target = True
return x1, y1, in_target
#---
speed = 10
# bullet position
x1 = 10
y1 = 0
# taget possition
x2 = 120
y2 = 10
print('x: {:6.02f} | y: {:6.02f}'.format(x1, y1))
in_target = False
while not in_target:
x1, y1, in_target = move(x1, y1, x2, y2, speed)
print('x: {:6.02f} | y: {:6.02f}'.format(x1, y1))
结果
x: 10.00 | y: 0.00
x: 19.96 | y: 0.91
x: 29.92 | y: 1.81
x: 39.88 | y: 2.72
x: 49.84 | y: 3.62
x: 59.79 | y: 4.53
x: 69.75 | y: 5.43
x: 79.71 | y: 6.34
x: 89.67 | y: 7.24
x: 99.63 | y: 8.15
x: 109.59 | y: 9.05
x: 119.55 | y: 9.96
x: 120.00 | y: 10.00
顺便说一句:如果 target
没有改变位置或者 bullet
没有改变 angle
那么你可以只计算一次 cx,cy
.
BTW: if target
doesn't change place or bullet
doesn't change angle
then you can calculate cx,cy
only once.