Dhanush
Dhanush

Reputation: 19

How to use collidepoint() in pygame?

I am making a soccer game. Where pygame should detect a collision between the ball and the player. I am not sure if I am using the right function or I have to use some logic to detect it. If you do need to use some logic. Could you help me understand the logic.

Upvotes: 0

Views: 1246

Answers (1)

Kingsley
Kingsley

Reputation: 14906

Unless your ball is a single pixel, you probably want to use colliderect().

Create a PyGame Rect for you player, and use the (x,y) of that rect to move it around, and to blit it. Similarly for the ball.

This might give you some code like:

player_img = pygame.image.load( "player.png" ).convert_alpha()
player_rect= player_img.get_rect()
player_rect.topleft = ( player_start_x, player_start_y )

ball_img   = pygame.image.load( "ball.png" ).convert_alpha()
ball_rect  = ball_img.get_rect()
ball_rect.topleft = ( ball_start_x, ball_start_y )

And a very simple ball-collision function. The colliderect() simply returns True if the parameter-rect overlaps geometrically with the base rect. Since balls are typically round(ish), eventually you could investigate using "masked" collisions, which will only collide where the actual ball is in the image (e.g. not the corners) - but for now don't worry about it.

def playerAtBall( player_rect, ball_rect ):
    result = False
    if ( player_rect.colliderect( ball_rect ) ):
        result = True
    return result

Then later put it all together in your main loop:

### Main Loop
clock = pygame.time.Clock()
done = False
while not done:

    # Handle user-input
    for event in pygame.event.get():
        if ( event.type == pygame.QUIT ):
            done = True

    # Movement keys
    keys = pygame.key.get_pressed()
    if ( keys[pygame.K_LEFT] ):
        print("Move left")
        player_rect.x -= 1
    if ( keys[pygame.K_RIGHT] ):
        print("Move right")
        player_rect.x += 1

    # Is the player at the ball?
    if ( playerAtBall( player_rect, ball_rect ) ):
        print( "PLAYER AT BALL - DO SOMETHING!" )

    # redraw the screen
    window.fill( GREEN )
    window.blit( player_img, player_rect )
    window.blit( ball_img, ball_rect )
    pygame.display.flip()

    # Clamp FPS
    clock.tick_busy_loop(60)

pygame.quit()

NOTE: This is not tested, debugged code, just written off the top of my head. Expect typos, errors, etc.

Upvotes: 1

Related Questions