0
\$\begingroup\$

so I have this basic game I made with pygame, in the game I have this player sprite:

which is 16x28, problem is: all other sprites in the game are 16x16, so I want the player's hitbox to be 16x16 as well, here's what I have for that:

import pygame

class Player:
    def __init__(self, screen):
        self.screen = screen
        self.image = pygame.image.load("player.png")
        self.rect = pygame.rect(0, 0, 16, 16)

    def collide_test(self):
        # collision test here using self.rect

    def move(self):
        # player movement here self.rect

    def render(self):
        pygame.draw.rect(self.screen, "RED", self.rect)
        self.screen.blit(self.image, self.rect)

And this works fine, using self.rect for collision test and movement, and self.image for blitting the sprite, but now the player's hitbox is bound to the upper part of the sprite, which is not what I want, so I tried this:

import pygame

class Player:
    def __init__(self, screen):
        self.screen = screen
        self.image = pygame.image.load("player.png")
        self.rect = pygame.rect(0, 0, 16, 16)

    def collide_test(self):
        # collision test here using self.rect

    def move(self):
        # player movement here self.rect

    def render(self):
        pygame.draw.rect(self.screen, "RED", self.rect)
        self.screen.blit(self.image, (self.rect.x, self.rect.y - 12)) # blitting the sprite 12 pixels down, which is the difference between 28 and 16

And now this works exactly like I wanted, but it seems like this solution is not so good, any ideas on a more efficient solution? Thanks in advance.

\$\endgroup\$
1
  • 2
    \$\begingroup\$ What is it about your current solution that you feel is "not so good"? What should answers focus on improving about it? \$\endgroup\$
    – DMGregory
    Aug 8 '21 at 1:13

You must log in to answer this question.

Browse other questions tagged .