0

Here is the code that tries to make my player stand on terrain -

class Player(pygame.sprite.Sprite):
    
    def __init__(self):
        ...

        self.image = self.images_run_list[self.hero_index]
        self.rect = self.image.get_rect(center=(200, 200))

        ...

    def vertical_collision(self):
        import playground

        for terrain in playground.terrain_group:

            if self.rect.colliderect(terrain.rect):
                print('collision')
                if self.rect.bottom < terrain.rect.top:
                    # self.rect.bottom = terrain.rect.top
                    print('rest on the terrain')

I was able to print "collision", but unable to print "rest on the terrain". That means that I cannot reach the second if statement, if self.rect.bottom < terrain.rect.top: . Could someone recognize the problem here?

Here is the implementation of terrain from playground.py -

terrain_group = pygame.sprite.Group()

# Timer
timer = pygame.USEREVENT + randint(0, 1)
pygame.time.set_timer(timer, 1500)

while True:

    # this loop ques a user's command and execute according to the code written in the loop
    for event in pygame.event.get():
        if event.type == timer:
            terrain_group.add(Terrains(choice([1, 2, 3])))
            terrain_group.add(Terrains(choice([1, 2, 3, 3])))
            terrain_group.add(Terrains(choice([2, 3, 3])))

    # calling terrain
        terrain_group.draw(screen)
        terrain_group.update()  #

2 Answers2

0

Vertical coordinates orientation in Pygame, unlike how we learn in maths, is smaller numbers are higher on the screen, not lower.

Without seeing all the code, I suppose that you would want the condition to be true when the bottom of the player's rect is bellow the top of the terrain's rect - and, if that is the case, your condition is reversed - you should test for:

if self.rect.bottom >= terrain.rect.top:

instead.

jsbueno
  • 99,910
  • 10
  • 151
  • 209
  • 1
    Sorry but you suggestion didn't work. How is my `if` statement logically incorrect? My `if` statement is trying to set the condition that if `self.rect.bottom` is smaller than `terrain.rect.bottom` then that if statement is true. Wouldn't your suggestion mean the vice versa of my logic? – Parth Gupta Aug 02 '22 at 20:07
0

Resolved. The error was not in my code, instead the error was in the pixel image I was using. The rectangle of my pixel image included blank spaces.

  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Aug 05 '22 at 15:58