how to make circles bounce of each other with the same speed?

I'm currently following along a tutorial to get a better understanding of pygame. What I'm trying to do now is make this program that currently spawns 100 random circles (balls) actually bounce off each-other when they come in contact/collide.

As of now I have it detecting if the two circles collide and bounce (sorta) off each-other. I looked around and found many posts asking somewhat the same question but the thing I kept noticing is that a lot of them require certain attributes that each ball has (velocity, radius, etc..) which I don't really have. What I have now is when it detects a collision it simply swaps the x and y's of the balls to create a bounce affect, the issue is that it seems very buggy and a lot of the circles start spazzing out.

So I'm wondering if I need to add more attributes to each individual ball or am incorrectly swapping the x and y's? I'm not entirely sure if I'm on the right track or if I'm just overthinking this since all I'm trying to do is create a very simple bounce affect where they all just have a constant speed.

code that I'm using to create the bounce :

for i in range(0, len(ball_list)):
    for j in range(i + 1, len(ball_list)):
        if pygame.Vector2(ball_list[i].x, ball_list[i].y).distance_to(
                pygame.Vector2(ball_list[j].x, ball_list[j].y)) <= 25:
            ball_list[i].x, ball_list[j].x = ball_list[j].x, ball_list[i].x
            ball_list[i].y, ball_list[j].y = ball_list[j].y, ball_list[i].y

whole-code:

import pygame
import random

# Define some colors
BLACK = (0, 0, 0)

SCREEN_WIDTH = 1000
SCREEN_HEIGHT = 1000
BALL_SIZE = 25

class Ball:
    """
    Class to keep track of a ball's location and vector.
    """

    def __init__(self):
        self.x = 0
        self.y = 0
        self.change_x = 0
        self.change_y = 0
        self.color = None


def make_ball():
    """
    Function to make a new, random ball.
    """
    ball = Ball()
    # Starting position of the ball.
    # Take into account the ball size so we don't spawn on the edge.
    ball.x = random.randrange(BALL_SIZE, SCREEN_WIDTH - BALL_SIZE)
    ball.y = random.randrange(BALL_SIZE, SCREEN_HEIGHT - BALL_SIZE)

    # Speed and direction of rectangle
    ball.change_x = random.randrange(-2, 3)
    ball.change_y = random.randrange(-2, 3)

    ball.color = (random.randrange(256), random.randrange(256), random.randrange(256))

    return ball


def main():
    """
    This is our main program.
    """
    pygame.init()

    # Set the height and width of the screen
    size = [SCREEN_WIDTH, SCREEN_HEIGHT]
    screen = pygame.display.set_mode(size)

    pygame.display.set_caption("Bouncing Balls")

    # Loop until the user clicks the close button.
    done = False

    # Used to manage how fast the screen updates
    clock = pygame.time.Clock()

    ball_list = []

    ball = make_ball()
    ball_list.append(ball)
    for i in range(100):
        ball = make_ball()
        ball_list.append(ball)

    # -------- Main Program Loop -----------
    while not done:
        # --- Event Processing
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                done = True
            elif event.type == pygame.KEYDOWN:
                # Space bar! Spawn a new ball.
                if event.key == pygame.K_SPACE:
                    ball = make_ball()
                    ball_list.append(ball)


        # --- Logic
        for ball in ball_list:
            # Move the ball's center
            ball.x += ball.change_x
            ball.y += ball.change_y

            # Bounce the ball if needed
            if ball.y > SCREEN_HEIGHT - BALL_SIZE or ball.y < BALL_SIZE:
                ball.change_y *= -1
            if ball.x > SCREEN_WIDTH - BALL_SIZE or ball.x < BALL_SIZE:
                ball.change_x *= -1

        for i in range(0, len(ball_list)):
            for j in range(i + 1, len(ball_list)):
                if pygame.Vector2(ball_list[i].x, ball_list[i].y).distance_to(
                        pygame.Vector2(ball_list[j].x, ball_list[j].y)) <= 25:
                    ball_list[i].x, ball_list[j].x = ball_list[j].x, ball_list[i].x
                    ball_list[i].y, ball_list[j].y = ball_list[j].y, ball_list[i].y

        # --- Drawing
        # Set the screen background
        screen.fill(BLACK)

        # Draw the balls
        for ball in ball_list:
            pygame.draw.circle(screen, ball.color, [ball.x, ball.y], BALL_SIZE)

        # --- Wrap-up
        # Limit to 60 frames per second
        clock.tick(60)

        # Go ahead and update the screen with what we've drawn.
        pygame.display.flip()

    # Close everything down
    pygame.quit()


if __name__ == "__main__":
    main()


Read more here: https://stackoverflow.com/questions/66270255/how-to-make-circles-bounce-of-each-other-with-the-same-speed

Content Attribution

This content was originally published by Hisoka at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: