Fron
Fron

Reputation: 11

How do you program collision in classes?

I've been having a hard time getting collision to work. I'm new and don't know the in and outs with coding so please can you explain your reasoning.

Here's a simple of some code:

def __init__(self, x, y, width, height, sprite):
    self.x = player_x
    self.y = player_y
    self.width = player.width
    self.height = player.height
    self.col = pygame.sprite.collide_rect(self, sprite)
    pygame.sprite.Sprite.__init__(self)

def velocity_player(self):
    player_vertical_velocity = 0
    player_horizontal_velocity = 0
    player_y = player_y + player_vertical_velocity
    player_x = player_x + player_horizontal_velocity
    player_fr = 5

def render(self):
    player_surface = pygame.image.load("Bunny.png")
    player_surface.set_colorkey(TRANSPARENT_GREEN)

    player_left = pygame.image.load("Bunny_left.png")
    player_left.set_colorkey(TRANSPARENT_GREEN)

    player_left = pygame.image.load("Bunny_left.png")
    player_left.set_colorkey(TRANSPARENT_GREEN)

    player_fall = pygame.image.load("Bunny_Fall.png")
    player_fall.set_colorkey(TRANSPARENT_GREEN)
    
    player_jump = pygame.image.load("Bunny_r_Jump.png")
    screen.blit(player_surface, [player_x, player_y])

Upvotes: 0

Views: 827

Answers (1)

Rabbid76
Rabbid76

Reputation: 211146

First, start by learning the concept of Classes (see also Python - Classes and OOP Basics). The collision must be detected in every frame. Usually you don't want to do it in the constrictor of a class. See How do I detect collision in pygame?.

When using pygame.sprite.Sprites and pygame.sprite.Groups, collision is detected by functions like pygame.sprite.spritecollide() and pygame.sprite.groupcollide(). However, collision detection is usually not performed in the Sprite class. This is done in the outer code that manages the Sprites and the interaction between the Sprites.

Minimal example:

import pygame
pygame.init()
window = pygame.display.set_mode((250, 250))

class RectSprite(pygame.sprite.Sprite):
    def __init__(self, color, x, y, w, h):
        super().__init__() 
        self.image = pygame.Surface((w, h))
        self.image.fill(color)
        self.rect = pygame.Rect(x, y, w, h)

player = RectSprite((255, 0, 0), 0, 0, 50, 50)
obstacle1 = RectSprite((128, 128, 128), 50, 150, 50, 50)
obstacle2 = RectSprite((128, 128, 128), 150, 50, 50, 50)
all_group = pygame.sprite.Group([obstacle1, obstacle2, player])
obstacle_group = pygame.sprite.Group([obstacle1, obstacle2])

run = True
while run:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    player.rect.center = pygame.mouse.get_pos()
    collide = pygame.sprite.spritecollide(player, obstacle_group, False)
    
    window.fill(0)
    all_group.draw(window)
    for s in collide:
        pygame.draw.rect(window, (255, 255, 255), s.rect, 5, 1)
    pygame.display.flip()

pygame.quit()

Upvotes: 2

Related Questions