I have created the collision detection code for my player but I can't seem to figure out how to stop the character from going through the walls.
import pygame
from pygame.locals import (
K_UP,
K_DOWN,
K_LEFT,
K_RIGHT,
K_ESCAPE,
KEYDOWN,
KEYUP,
QUIT,
)
pygame.init()
clock = pygame.time.Clock()
ScreenWidth = 1920
ScreenHeight = 1080
screen = pygame.display.set_mode((ScreenWidth, ScreenHeight))
pd_surface = pygame.display.set_mode((ScreenWidth, ScreenHeight))
running = True
pygame.display.set_caption("Maze Game")
#object details
playerImg = pygame.image.load('player.png').convert_alpha()
playerImg_mask = pygame.mask.from_surface(playerImg)
playerx = 550
playery = 200
playerx_change = 0
playery_change = 0
player_rect = playerImg.get_rect(center=(playerx,playery))
backgroundImg = pygame.image.load('Level one.png')
mazeImg = pygame.image.load('Maze Level One.png')
#backgroundImg_mask = pygame.mask.from_threshold(backgroundImg, pygame.Color('black'), (0, 0, 0, 255))
mazeImg_mask = pygame.mask.from_surface(mazeImg)
bx = 90
by = 108
mx = 300
my = 200
maze_pos = (300, 200)
#objects
def background():
screen.blit(backgroundImg, (by, bx))
def player(rect):
screen.blit(playerImg, rect) # no xy needed
def maze():
screen.blit(mazeImg, maze_pos)
#main loop
while running:
for event in pygame.event.get():
if event.type == KEYDOWN:
if event.key == K_ESCAPE: #move this under the existing keydown for player pos change
running = False
elif event.type == QUIT:
running = False
if event.type == KEYDOWN:
if event.key == K_LEFT:
playerx_change = -5
if event.key == K_RIGHT:
playerx_change = 5
if event.key == K_UP:
playery_change = -5
if event.key == K_DOWN:
playery_change = 5
if event.type == KEYUP:
if event.key == K_LEFT or event.key == K_RIGHT:
playerx_change = 0
if event.key == K_UP or event.key == K_DOWN:
playery_change = 0
player_rect.x += playerx_change
player_rect.y += playery_change
if player_rect.centerx <=550:
player_rect.centerx = 550
elif player_rect.centerx >=1450:
player_rect.centerx = 1450
if player_rect.centery <=150:
player_rect.centery = 150
elif player_rect.centery >=730:
player_rect.centery=730
offset_x = maze_pos[0] - player_rect.left
offset_y = maze_pos[1] - player_rect.top
result = playerImg_mask.overlap(mazeImg_mask, (offset_x, offset_y))
if result:
print(result)
background()
maze()
player(player_rect)
pygame.display.update()
I have tried decreasing the player_x change by a 5 when the collision between the player and the wall is detected but nothing happens, the player simply goes through the wall.