Aug-19-2022, 03:51 PM
(This post was last modified: Aug-19-2022, 03:51 PM by deanhystad.)
The floor is not the problem. You can stop collisions by setting speed to zero. You just aren't properly handling all the conditions.
It is actually quite easy. The algorithm can be summed up as:
1: Test if move results in collision
2: If collision detected, don't move
3: If collision not detected, move.
It is actually quite easy. The algorithm can be summed up as:
1: Test if move results in collision
2: If collision detected, don't move
3: If collision not detected, move.
def move(x, y, xvel, yvel): # Check if x+xvel results in a collision playerrect.x, playerrect.y = x + xvel, y for tile in tile_rects: if playerrect.colliderect(tile): xvel = 0 # Don't move in x direction break # Check if y+yvel results in a collision playerrect.x, playerrect.y = x, y + yvel for tile in tile_rects: if playerrect.colliderect(tile): yvel = 0 # Don't move in y direction break return x + xvel, y + yvel, yvelYou have a slight complication in the way that gravity changes your yvel. That is why velocity is returned.
while True: # Process all events first for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == KEYDOWN: if event.key in (K_RIGHT, K_d): player_speed = 5 elif event.key in (K_LEFT, K_a): player_speed = -5 elif event.key in (K_UP, K_w): player_y_momentum = -5 elif event.type == KEYUP: if event.key in (K_RIGHT, K_d, K_LEFT, K_a): # Stop moving in x when key is released player_speed = 0 # Update player momentum player_y_momentum = min(3, player_y_momentum + 0.2) # Check for collisions. A collision will stop the player from moving in the direction that # resulted in the collision. playerx, playery, player_y_momentum = move( playerx, playery, playerspeed, player_y_momentum ) # draw the background, the tiles and the player last.Maybe the trickiest thing is order. One of your problems is you checked for collisions first, then you processed events and did your momentum calc. You want checking for collisions to be the last thing you do before moving the player. move() cannot prevent the player running into things if you ignore or override the actions taken to prevent collisions.