我建议计算跟随者和精灵之间的距离以及从 ( follower_x
, follower_y
) 到 ( mainsprite_x
, mainsprite_y
) 的单位方向向量。
距离可以通过计算欧几里得距离得到。Pygame 提供distance_to()
了这一点。单位方向向量可以通过将方向向量除以距离或通过归一化 ( normalize()
) 方向向量来计算:
target_vector = Vector2(mainsprite_x, mainsprite_y)
follower_vector = Vector2(follower_x, follower_y)
distance = follower_vector.distance_to(target_vector)
direction_vector = target_vector - follower_vector
if distance > 0:
direction_vector /= distance
现在您可以定义精灵的精确step_distance
方向并移动到跟随者 int 方向:
if distance > 0:
new_follower_vector = follower_vector + direction_vector * step_distance.
定义 amaximum_distance
和 a minimum_distance
。最小步距为:
min_step = max(0, distance - maximum_distance)
最大步距为
max_step = distance - minimum_distance
把它们放在一起:
minimum_distance = ???
maximum_distance = ???
target_vector = Vector2(mainsprite_x, mainsprite_y)
follower_vector = Vector2(follower_x, follower_y)
new_follower_vector = Vector2(follower_x, follower_y)
distance = follower_vector.distance_to(target_vector)
if distance > minimum_distance:
direction_vector = (target_vector - follower_vector) / distance
min_step = max(0, distance - maximum_distance)
max_step = distance - minimum_distance
step_distance = min_step + (max_step - min_step) * LERP_FACTOR
new_follower_vector = follower_vector + direction_vector * step_distance
最小的例子: repl.it/@Rabbid76/PyGame-FollowMouseSmoothly
import pygame
LERP_FACTOR = 0.05
minimum_distance = 25
maximum_distance = 100
def FollowMe(pops, fpos):
target_vector = pygame.math.Vector2(*pops)
follower_vector = pygame.math.Vector2(*fpos)
new_follower_vector = pygame.math.Vector2(*fpos)
distance = follower_vector.distance_to(target_vector)
if distance > minimum_distance:
direction_vector = (target_vector - follower_vector) / distance
min_step = max(0, distance - maximum_distance)
max_step = distance - minimum_distance
step_distance = min_step + (max_step - min_step) * LERP_FACTOR
new_follower_vector = follower_vector + direction_vector * step_distance
return (new_follower_vector.x, new_follower_vector.y)
pygame.init()
window = pygame.display.set_mode((500, 500))
clock = pygame.time.Clock()
follower = (100, 100)
run = True
while run:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
player = pygame.mouse.get_pos()
follower = FollowMe(player, follower)
window.fill(0)
pygame.draw.circle(window, (0, 0, 255), player, 10)
pygame.draw.circle(window, (255, 0, 0), (round(follower[0]), round(follower[1])), 10)
pygame.display.flip()