Rect won't update position when the sprite it is taken from moves

Question:

player_rect = Pfront_n.get_rect()

Here ‘Pfront_n’ is a sprite, and I am getting a rect for that sprite. This is outside of the main loop. When inside the main loop, print(player_rect) shows that when my player moves, the rect doesn’t follow. My players movement system is a velocity based one, if that makes any difference. How can I have the rect stay around the player?

Following this, I have another similar question…

for layer in room2:
        r_x = 0
        for tile in layer:  
            if tile == '2':
                bat_create()    
            if tile == '1':
                screen.blit(grass, (r_x*40, r_y*40))        
            if tile != '0':
                tile_rects.append(pygame.Rect)
            r_x += 1
        r_y += 1 

Outside the main loop, I have created a rect for grass in the same was as I have for my player. The method I am using in the above code has multiple grass blocks appear in positions pre-determined by an array. How can I get the rects for each individual grass block?
Fairly Irrelevant Sidenote for Context -The ultimate goal is to use my players rect, and the grass rect so my player gets stopped when hitting the grass. Any help on either of these questions would be great. Thanks!

Asked By: Owen Penn

||

Answers:

The class Sprite has no method get_rect. Probably Pfront_n is a Surface. A surface has no position, not, a surface is blit at a position onto another surface. The x and y coordinate which is returned by get_rect() is (0, 0). But you can set the position. The keyword arguments to get_rect are set to the corresponding virtual attribute of pygame.Rect. e.g:
(player_x, player_y is supposed to be the position of the player)

player_rect = Pfront_n.get_rect(topleft = (player_x, player_y)) 

What is tile_rects.append(pygame.Rect) supposed to do? pygame.Rect is a class. If you want to append a pygame.Rect object, which represents a tile to tile_rects, then it has to be:

tile_rects.append(pygame.Rect(r_x*40, r_y*40, 40, 40))
Answered By: Rabbid76
Categories: questions Tags: , , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.