Sunday, June 19, 2022
HomeGame Developmentpython - Utilizing collision with lessons in pygame

python – Utilizing collision with lessons in pygame


There are a few methods you’ll be able to detect collisions in Pygame, the simplest on this case, I feel, is to make use of Rect.colliderect().

To make use of .colliderect() you first want some rects. Within the case of the paddles that is straightforward, as a result of your initialization parameters of x, y, width, top is a rect. To get the rect for the circle you should utilize a line much like:

ballRect = pygame.draw.circle(show,(self.coloration),(self.posx,self.posy),self.radius,0)

Now that you’ve got the three rects, in your ball class check for collisions:

def collideTest(self):
    bump = self.ballRect.colliderectlist([paddle1.rect, paddle2.rect])
    if bump >= 0:
        #bump holds both 0 or 1 indicating which paddle was collided with

So, now a few suggestions.

Courses ought to solely deal with the issues which pertain to the category itself. They should not be checking for keypresses, for instance. Keypresses and different enter must be checked for in your foremost sport loop. The objects ought to preserve observe of issues like their very own place, look, motion, and many others.

A category’s strategies ought to, once more, pertain to the category. Your paddles and your ball, for instance, ought to understand how to attract themselves, so yeah, you need to have a “drawing” technique. (I normally name mine both .draw() or .present().)

As I already indicated above, it must be your ball object which check for the collision, the reason is that it’s the ball which should react to the collision. You also needs to add a few rects on the sides of the show which signify the targets. The ball object ought to decide whether or not it has collided with a paddle or a objective and react appropriately, both by reflecting off the paddle or by updating the suitable rating.

You possibly can add a scoreboard class which retains observe of and shows the rating for each gamers.

Good luck with it.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments