So i'm making a tile based platformer and i cant get collisions to work.
This code in the main loop displays the tiles:
tile_rects = []
y = 0
for layer in game_map:
x = 0
for tile in layer:
if tile == '1':
display.blit(dirt, (x * tile_size, y * tile_size))
if tile == '2':
display.blit(grass, (x * tile_size, y * tile_size))
if tile != '0':
tile_rects.append(pygame.Rect(x * tile_size, y * tile_size, tile_size, tile_size))
x += 1
y += 1
And this code is supposed to make the collisions work but somehow it doesnt, this is in the player class.
def collisions(self):
global tile_rects
self.rect.x += self.x_vel
self.rect.y += self.y_vel
for tile_rect in tile_rects:
if self.rect.colliderect(tile_rect):
if abs(tile_rect.top - self.rect.bottom) < 10:
self.y_vel -= 1
if abs(tile_rect.bottom - self.rect.top) < 10:
self.y_vel += 1
if abs(tile_rect.right - self.rect.left) < 10:
self.x_vel -= 1
if abs(tile_rect.left - self.rect.right) < 10:
self.x_vel += 1
else: tile_rects = []
Any fixes?