Im making a "catcher" style game in python, where the player has to collect "Gems", and avoid the "Spikes". However the games collision detection is off by quite a lot. When I run the game, everything is going well. The player is moving, the objects are falling from the correct positions. But when the collision is detected it is detected early. How can I improve the collision detection so it can detect more accurate collisions with either of the objects? Here is part of the code including the Player, Gem, and Spike class. The full code, with graphics is in the github link below. Any help is appriciated!
class Player(pygame.sprite.Sprite):
def __init__(self):
global game_state
# super().__init__()
self.player_surf = pygame.image.load('game graphics/player_stand.png').convert_alpha()
#scaled player image
self.player_surf = pygame.transform.scale(self.player_surf,(500,500))
self.rect = self.player_surf.get_rect(midbottom = (x,y))
self.x_speed = 5
self.health = 5
self.score = 0
class Gem(pygame.sprite.Sprite):
def __init__(self):
self.x = random.randrange(0, screen_w)
self.y = -20
self.vel = 4
self.gem_image = [pygame.image.load('gems & spikes/greenGem.png'),
pygame.image.load('gems & spikes/redGem.png'),
pygame.image.load('gems & spikes/blueGem.png'),
pygame.image.load('gems & spikes/yellowGem.png')]
self.gem_image = [pygame.transform.scale(img, (90, 90)) for img in self.gem_image]
self.counter = 0
self.rect = self.gem_image[counter].get_rect(midbottom=(self.x, self.y))
self.update_y()
def update_y(self):
self.y += self.vel
self.rect = self.gem_image[self.counter].get_rect(midbottom=(self.x, self.y))
self.collide = self.rect.colliderect(player.rect)
if self.y > screen_h:
self.y = -20
self.x = random.randrange(0, screen_w)
self.counter = (self.counter + 3) % len(self.gem_image)
if self.collide:
self.y = 0
self.x = random.randrange(0, screen_w)
player.score += 1
class Spike(pygame.sprite.Sprite):
def __init__(self):
self.x = random.randrange(0,screen_w)
self.y = -20
self.vel = 2
self.spike_image = pygame.image.load('gems & spikes/spike.png')
self.spike_image = pygame.transform.scale(self.spike_image,(120,120))
self.rect = self.spike_image.get_rect(midbottom = (x,y))
self.update_y()
def update_y(self):
self.y += self.vel
self.rect = self.spike_image.get_rect(midbottom=(self.x, self.y))
self.collide = self.rect.colliderect(player.rect)
if self.y > screen_h:
self.y = -20
self.x = random.randrange(0, screen_w)
if self.collide:
player.health -= 1
self.y = -20
self.x = random.randrange(0, screen_w)
Github Repository: Cave-Of-Doom-
Here is a video of the problem on youtube: https://youtu.be/J5sGUwhVh4s