How to make a circle move diagonally from corner to corner in pygame

I will offer a more general approach. Define a list of positions (circle_pos_list) that the object should visit on its way. Set the start position (circle_pos), the speed (circle_speed) and the index of the next target position in the list (next_pos_index).

circle_pos_list = [(100, 100), (200, 150), (100, 150)]
circle_pos = circle_pos_list[0]
circle_speed = 5
next_pos_index = 1

Use pygame.math.Vector2 to calculate the current distance vector of the circle to the next target position in the list:

circle_dir = pygame.math.Vector2(circle_pos_list[next_pos_index]) - circle_pos

If the distance to the target is less than the speed of the circle, step on the target and change the target location index to the next target:

if circle_dir.length() < circle_speed:
    circle_pos = circle_pos_list[next_pos_index]
    next_pos_index = (next_pos_index + 1) % len(circle_pos_list)

Otherwise, take a step along the vector to the next destination:

circle_dir.scale_to_length(circle_speed)
new_pos = pygame.math.Vector2(circle_pos) + circle_dir
circle_pos = (new_pos.x, new_pos.y)

Changes in your code:

def main():
    # [...]

    blue_circ = pygame.Surface((24, 24))
    blue_circ.set_colorkey((0, 0, 0))
    pygame.draw.circle(blue_circ, (0, 0, 255), (12, 12), 12)

    # [...]

    circle_pos_list = [(100, 100), (200, 150), (100, 150)]
    circle_pos = circle_pos_list[0]
    circle_speed = 5
    next_pos_index = 1

    # LOOP
    while keepGoing:
        # [...]

        circle_dir = pygame.math.Vector2(circle_pos_list[next_pos_index]) - circle_pos
        if circle_dir.length() < circle_speed:
            circle_pos = circle_pos_list[next_pos_index]
            next_pos_index = (next_pos_index + 1) % len(circle_pos_list)
        else:
            circle_dir.scale_to_length(circle_speed)
            new_pos = pygame.math.Vector2(circle_pos) + circle_dir
            circle_pos = (new_pos.x, new_pos.y)

        # [...]

        screen.blit(blue_circ, (round(circle_pos[0]), round(circle_pos[1])))

        # [...]

Leave a Comment