William Redding
William Redding

Reputation: 33

Pygame Custom rect for collision detection

I have managed to use sprite collide to get a player to collide with another sprite and it works well.

However, the spritecollide function only allows it (as far as I can figure out at least) to collide with the rect called self.rect

I have a custom rect called self.hitbox which I want my player to collide with as the hitbox rect is different size to the inbuilt rect itself

Here is my code for the collision with the self.rect

def collide_blocks(self, direction):

    hits = pygame.sprite.spritecollide(self, self.game.block_objects, False)
          
    if hits:
        for i in hits:
            if direction == "x":
              if self.x_change > 0:
                self.rect.x = i.rect.left - self.rect.width
              if self.x_change < 0:
                self.rect.x = i.rect.right 
            if direction == "y":
              if self.y_change > 0:
                self.rect.y = i.rect.top - self.rect.height 
              if self.y_change < 0:
                self.rect.y = i.rect.bottom

How can adapt my code to make it collide with i.hitbox instead of i.rect (I = the sprite collided with)

Upvotes: 1

Views: 452

Answers (1)

Rabbid76
Rabbid76

Reputation: 210890

The 4th argument of pygame.sprite.spritecollide can be a user defined callback function used to calculate if two sprites are colliding:

def hitbox_collide(sprite1, sprite2):
    return sprite1.hitbox.colliderect(sprite2.hitbox)
hits = pygame.sprite.spritecollide(self, self.game.block_objects, False, hitbox_collide)

Upvotes: 1

Related Questions