Python.Collision of two objects in pygame

How do I implement a collision in my code?

import pygame
window=pygame.display.set_mode((700, 700))
pygame.display.set_caption('PYWINDOW')
screen=pygame.Surface((700, 700))
run=True
class Ball():
    def __init__(self, speed, width, height, oX, oY, img):
        self.speed=speed
        self.width=width
        self.height=height
        self.reverseX=False
        self.reverseY=False
        self.height=height
        self.x=oX
        self.y=oY
        self.img=img
    def drawAndMove(self, holst):
        # oX
        if self.reverseX:
            if self.x>0:
                self.x-=0.9*self.speed
            else:
                self.reverseX=False
        elif self.x<700-self.width:
            self.x+=1.3*self.speed
        else:
            self.reverseX=True
        # oY
        if self.reverseY:
            if self.y>0:
                self.y-=0.8*self.speed
            else:
                self.reverseY=False
        elif self.y<700-self.height:
            self.y+=1.1*self.speed
        else:
            self.reverseY=True
        holst.blit(self.img, (self.x, self.y))



def isQuit():
    global run
    for e in pygame.event.get():
        if e.type == pygame.QUIT:
            run=False

    
bimg=pygame.image.load('/home/korobeinikovi/ball.png')

ball1=Ball(1, 48, 46, 100, 100, bimg)
ball2=Ball(1, 48, 46, 100, 150, bimg)
while run:
    screen.fill((0, 100, 0))
    ball1.drawAndMove(screen)
    ball2.drawAndMove(screen)
    window.blit(screen, (0, 0))
    isQuit()
    pygame.display.flip()
pygame.quit()
Author: Igorok, 2020-08-05

1 answers

I would suggest that you draw the ball not as width and height, as well as oX and oY, but as the Radius and center of the ball. Namely and also R , oX and oY. This will make it easier for you to make comparisons for collisions, namely:

The collision of two balls is their contact, at which the distance between them is 0. That is, when they collide, the distance between their centers is equal to the sum of their radii R. The distance between two points on the plane is calculated by the formula (I translate to putkhon):

import math
distance = math.sqrt( (ball1.oX - ball2.oX) ** 2 +  (ball1.oY - ball2.oY) ** 2 )

Next, we compare if distance == ball1.R + ball2.R, then they collided. But it may be that our balls will pass through each other a little bit because of something, which means that our formula will not work, so I suggest putting distance <= ball1.R + ball2.R.

As a result, we enter it in the general loop for verification:

while Run:
    ...
    distance = math.sqrt( (ball1.oX - ball2.oX) ** 2 +  (ball1.oY - ball2.oY) ** 2 )
    if distance <= ball1.R + ball2.R:
        function_of_collision_you_need()

All the best-beaver

 1
Author: DiHASTRO, 2020-08-05 10:38:22