I am currently working on a small project where I create a 2d game using pygame. But I am currently stuck with my collisions which are not working as I wished they do. I have a first function returning True or False when the character is in a boundary,
leaved = False
moving = False
player_collision = False
def Extracted_Data(x,y,x_speed,y_speed):
global player_collision
player_collision=False
Player_Hitbox = pygame.draw.rect(gameDisplay,'black',((screen_width-png_width/4)/2 - x_speed,(screen_height-png_height/8)/2 - y_speed , tile_size , 3/4*tile_size),width=1)
for row_index,row in enumerate(data):
for col_index,val in enumerate(row):
if val == 1025:
Boundary = pygame.draw.rect(gameDisplay,'red',(x + col_index * tile_size, y + row_index * tile_size , tile_size , tile_size),width=1)
if pygame.Rect.colliderect(Player_Hitbox,Boundary):
player_collision=True
return player_collision
Which I think is working properly as it prints 'Colliding' when it should. I then tried to detect if player_collision is True or False in my event.get() loop which is the part not doing the right thing.
while not leaved:
print(player_collision)
gameDisplay.fill('white')
Background(x,y)
Extracted_Data(x,y,x_speed,y_speed)
Player(Img_Position)
Foreground(x,y)
Text()
for event in pygame.event.get():
if event.type == pygame.QUIT:
leaved = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
Img_Position = Img_Positions.get("left")
player_collision = Extracted_Data(x,y,player_speed,0)
if player_collision == True:
print("left")
moving = False
x_speed = 0
else:
moving = True
x_speed = player_speed
if event.type == pygame.KEYUP:
if event.key == pygame.K_q or event.key == pygame.K_d:
moving = False
x_speed = 0
elif event.key == pygame.K_z or event.key == pygame.K_s:
moving = False
y_speed = 0
x += x_speed
y += y_speed
pygame.display.update()
clock.tick(FPS)
pygame.quit()
quit()
Even if the collision is detected, the player can still move in the boundary. It will only be stuck if the key is released in the boundary. I think the problems come from the recovery of the player_collision state but I don't know how to fix this. I do not get any error message. Thank you in advance for any answer !