Getting an enemy to follow a player takes some math. I suggest to use pygame.math.Vector2 for the computation.
Calculate the Euclidean distance between the enemy (follower_x, follower_y) to the player (player_x, player_y) and the unit direction vector from the enemy to the palyer. The Unit Vector can be computed by dividing the direction vector by the distance or by normalizing (normalize()) the direction vector:
target_vector = Vector2(player_x, player_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
Define an exact step_distance and move in the direction of the sprite along the direction vector from the enemy to the player
if distance > 0:
new_follower_vector = follower_vector + direction_vector * step_distance.
Define a minimum_distance and a maximum_distance between the player and the enemy. The minimum distance can be 0 and the maximum distance can be very large:
minimum_distance = 0
maximum_distance = 10000
Use this minimum and maximum to restrict the movement of the enemy:
min_step = max(0, distance - maximum_distance)
max_step = distance - minimum_distance
The enemy's movement speed can be constant
VELOCITY = 5
step_distance = min(max_step, max(min_step, VELOCITY))
or smoothed with an interpolation factor:
LERP_FACTOR = 0.05
step_distance = min_step + (max_step - min_step) * LERP_FACTOR
Minimal example:
repl.it/@Rabbid76/PyGame-FollowMouseSmoothly

import pygame
VELOCITY = 5
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(max_step, max(min_step, VELOCITY))
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()
pygame.quit()
exit()