Racey – Using Rect Collisions

Pygame has a Rect function we can use to determine if two objects collide.

We need to create a Rect for each instanace of our class and we need to create a Rect for the car.

but first

We are going to use the Rect function to determine the height and width of our images.

Near the top of your code just under where we load the image we want to add the following

carOriginalRect = carImg.get_rect()
dogOriginalRect = dogImg.get_rect()

Now we can use things like carOriginalRect.width

As both the instances of the class and the car are moving we also need to create the Rect as we check of a collision rather than using the one we created at the beginning

Create a function Coll within the class with the parameters of self and car_rect

def coll(self, car_rect):

We can create a Rect be providing x, y, width, height values

self.rect = pygame.Rect(self.position[0], self.position[1], dogOriginalRect.width, dogOriginalRect.height)

Now when can check if the two Rect collide and remove the instance that collided with the car

if pygame.Rect.colliderect(self.rect, car_rect):
    dogArray.remove(self)

Now we need to call the Coll function from within the game loop

We are already looping through are dog array to move and draw our instances, so we can add the coll call from there.

Since the Coll function removes any instances we have collided with, we should call the Coll function before we move and draw our instances.

First we have to create the Rect for our car
again, we need x,y,width and height

carRect = pygame.Rect(x,y,carOriginalRect.width,carOriginalRect.height)

Now we can call the Coll function and pass it the carRect

dog.coll(carRect)