我明白你为什么会坚持下去。另一个解决方案并没有真正解决像 unit1 处于 30 度和 unit2 处于 340 度这样的情况,它会在 360 度旋转到 0 度。代码可以进行一些清理,但我希望这会有所帮助。
import math
# calculate and return the distance unit2
# needs to move to reach unit1
def get_distance(unit1, unit2):
phi = abs(unit2-unit1) % 360
sign = 1
# used to calculate sign
if not ((unit1-unit2 >= 0 and unit1-unit2 <= 180) or (
unit1-unit2 <= -180 and unit1-unit2 >= -360)):
sign = -1
if phi > 180:
result = 360-phi
else:
result = phi
return result*sign
# distance unit2 needs to move to reach unit1
print get_distance(90,45) # output 45
print get_distance(270, 350) # output -80
print get_distance(350, 30) # output -40 (unit2 moves -40 degrees)
print get_distance(30, 350) # output 40
unit1 = 30
unit2 = 350
# then calculate distance to move by taking 20 from distance
distance_to_move = (get_distance(unit1, unit2) - 20)
print (unit2 + distance_to_move)%360 # new position 10
正如Tadhg 所指出的那样,我对其进行了一些更改,使其可以工作超过 360 度。 20 度的方差也没有那么硬编码。
import math
# calculate and return the distance unit2
# needs to move to reach unit1
def get_distance(unit1, unit2):
phi = (unit2-unit1) % 360
sign = -1
# used to calculate sign
if not ((phi >= 0 and phi <= 180) or (
phi <= -180 and phi >= -360)):
sign = 1
if phi > 180:
result = 360-phi
else:
result = phi
return (result*sign), sign
def get_sign(unit1, unit2):
phi = (unit2-unit1) % 360
sign = 1
if ((phi >= 0 and phi <= 180) or (
phi <= -180 and phi >= -360)):
sign = -1
return sign
def new_position(unit1, unit2, variance = 20):
distance_to_move, sign = get_distance(unit1, unit2)
variance*=sign
# %360 to keep it within the circle
return (unit2+distance_to_move-variance)%360
# distance unit2 needs to move to reach unit1
assert (get_distance(90,45) == (45, 1))
assert (get_distance(270, 350) == (-80, -1))
assert (get_distance(350, 30) == (-40, -1))
assert (get_distance(30, 350) == (40, 1))
assert (get_distance(50, 360*4) == (50, 1))
assert (get_distance(360*4, 50) == (-50, -1))
print "----------"
assert (new_position(90,45) == 70)
assert (new_position(270, 350) == 290)
assert (new_position(350, 30) == 10)
assert (new_position(30, 350) == 10)
assert (new_position(50, 360*4) == 30)
assert (new_position(360*4, 50) == 20)