So, I asked how to make a sprite collide with and image in Pygame, and somebody suggested using colors to detect collisions. I went to work on that. Now that I have finished that, the collision detection system is VERY janky. It works some of the time, but not all of the time. (keep in mind the object i am colliding with has multiple colors but ive coded that in) Please help!
#Imports needed libraries.
import pygame
#Initialises PyGame.
pygame.init()
#Sets window resolution, icon & title. Also gets required images.
win = pygame.display.set_mode((512,320))
pygame.display.set_caption("Maze Game")
window_icon = pygame.image.load("C:\\Users\\chizl\\Documents\\Images\\project_icon.png")
pygame.display.set_icon(window_icon)
level = pygame.image.load("C:\\Users\\chizl\\Documents\\Images\\bg-1.png")
#The necessary values for the player.
x = 40
y = 40
width = 16
height = 16
vel = 8
#While loop for window (put all code here).
run = True
while run:
pygame.time.delay(128)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
#Key presses.
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
x -= vel
if keys[pygame.K_RIGHT]:
x += vel
if keys[pygame.K_UP]:
y -= vel
if keys[pygame.K_DOWN]:
y += vel
#Collisions using colors.
color = (0, 0, 0, 0)
color = win.get_at((x, y))
if keys[pygame.K_LEFT] and color == (156, 156, 156, 255) or color == (127, 127, 127, 255) or color == (95, 95, 95, 255):
x += 8
elif keys[pygame.K_RIGHT] and color == (156, 156, 156, 255) or color == (127, 127, 127, 255) or color == (95, 95, 95, 255):
x -= 8
elif keys[pygame.K_UP] and color == (156, 156, 156, 255) or color == (127, 127, 127, 255) or color == (95, 95, 95, 255):
y += 8
elif keys[pygame.K_DOWN] and color == (156, 156, 156, 255) or color == (127, 127, 127, 255) or color == (95, 95, 95, 255):
y -= 8
#Window properties.
win.fill((255,255,255))
win.blit(level, (0,0))
pygame.draw.rect(win, (0,0,0), (x, y, width, height))
pygame.display.update()
pygame.quit()
#Chris L 2022