I've been having trouble with collisions in pygame. Specifically, I have a player and a list of walls, and if they collide, I'm supposed to prevent any more movement in that direction.
I've tried many guides but I can't seem to get this to work myself.
import pygame
pygame.init()
win = pygame.display.set_mode((800,600))
pygame.display.set_caption("Game")
playerX = 380 #Player X coordinate
playerY = 380 #Player Y coordinate
playerXVel = 10 #Horizontal Velocity
playerYVel = 10 #Vertical Velocity
overworld = (248, 192, 117)
run = True
while run: #The game starts running
win.fill(overworld)
pygame.time.delay(30)
for event in pygame.event.get(): #You can stop the game now too
if event.type == pygame.QUIT:
run = False
class Player: #This is you
def __init__(self):
self.rect = pygame.Rect(playerX,playerY,50,50)
player = Player()
class Wall: #The walls
def __init__(self, pos):
walls.append(self)
self.rect = pygame.Rect(pos[0], pos[1], 50, 50)
walls = []
keys = pygame.key.get_pressed() #To retain the feel of retro video games, I have made it impossible to walk diagonally
if keys[pygame.K_w] and not keys[pygame.K_a] and not keys[pygame.K_d]:
playerY -= playerYVel
if keys[pygame.K_a] and not keys[pygame.K_w] and not keys[pygame.K_s]:
playerX -= playerXVel
if keys[pygame.K_s] and not keys[pygame.K_a] and not keys[pygame.K_d]:
playerY += playerYVel
if keys[pygame.K_d] and not keys[pygame.K_s] and not keys[pygame.K_w]:
playerX += playerXVel
#I copied this section of code
#Credit: https://www.pygame.org/project-Rect+Collision+Response-1061-.html
level = [
"WWWWWWWWWWWWWWWW",
"W W",
"W W",
"W W",
"W W",
"W W",
"W W",
"W W",
"W W",
"W W",
"W W",
"WWWWWWWWWWWWWWWW",
]
x = y = 0
for row in level:
for col in row:
if col == "W":
Wall((x, y))
x += 50
y += 50
x = 0
#Drawing every rectangle in :3
pygame.draw.rect(win, (0, 255, 0), player.rect)
for wall in walls:
pygame.draw.rect(win, (143, 41, 3), wall.rect)
pygame.display.update()
pygame.quit()
So far so good. I have walls, I have a player, and that player can move. The player can, however, walk through the walls.
I want to put a piece of code in that prevents velocity being added or removed if the player collides with a wall. This what I've tried for walking upwards, but it just makes it so that I cannot walk upwards altogether
for allwalls in walls:
if not player.rect.colliderect(allwalls):
playerY -= playerYVel
Could anyone tell me what I'm doing wrong/what I should be entering into the code instead to prevent a player from moving through a wall?