Skip to content Skip to sidebar Skip to footer

Collision Detection Against Player And Blocks In The Map

I made a game map like this class Game_map: def __init__(self): self.land = pygame.image.load(r'C:\Users\name\OneDrive\Documents\A level python codes\final game\land.pn

Solution 1:

The straight forward method is to find the collisions of the player rectangle and the obstacle rectangles.

Create a list of the field indices of all obstacles:

obstacles = [(i, j) for i in range(len(game_map.layout))
                    for j in range(len(game_map.layout[i]))
                    if game_map.layout[i][j] == 1]

Setup a pygame.Rect for the player:

player_rect = pygame.Rect(player.x, player.y, player.width, player.height) 

Use colliderect() to find the collisions of the player and the obstacles:

hit = [obj for obj in obstacles
           if player_rect.colliderect(
               pygame.Rect(obj[0]*400-scroll[0], obj[1]*250-scroll[1], 400, 250))]

if any(hit):
    print("hit")

The more tricky by far more efficient method is to compute the field indices for the 4 corners of the player rectangle and to evaluate if one of the corners is in a field with an obstacle.

Setup the player rectangle:

player_rect = pygame.Rect(player.x, player.y, player.width, player.height) 

Compute the coordinates for corners of the rectangle:

player_corners = [player_rect.topleft, player_rect.topright, 
                  player_rect.bottomleft, player_rect.bottomright]

Compute the field indices, where the corner points are on:

corner_indices = [((p[0]+scroll[0])//400, (p[1]+scroll[1])//250) for p in player_corners]

Evaluate if any of the field contains an obstacle:

hit = [ind for ind in corner_indices if game_map.layout[ind[0]][ind[1]]]

if (any(hit)):
    print("hit")

Post a Comment for "Collision Detection Against Player And Blocks In The Map"