Player Movement

When we are playing a game, most of the time we have to move the player. If we want to move the player, we should add a move function to the Player class. The move function contains two arguments as dx and dy. The d stands for delta. But it's not not enough for moving the player. We need to update function for changing the player's position according to updated rect's positions. Well, it's not for just updating position, in addition, we will get events for the player object from the update function. Let's create these two function in the Player class:
class Player(pygame.sprite.Sprite):
    def __init__(self, sprites_group, pos, dim, col):
        ...

    def update(self):
        self.get_event()

    def get_event(self):
        keys = pygame.key.get_pressed()
        if keys[pygame.K_w]:
            self.move(0, -5)
        if keys[pygame.K_s]:
            self.move(0, +5)
        if keys[pygame.K_a]:
            self.move(-5, 0)
        if keys[pygame.K_d]:
            self.move(+5, 0)

    def move(self, dx, dy):
        self.rect.x += dx
        self.rect.y += dy
So, we typed get_event function for when we pressed the keys about direction, the player's position will be changed via move function. We are adding get_event function to the update function. The update function is already defined in Sprite class so it related sprite_group. If we update sprites_group, all update function of sprites will run. So we just add sprites_group.update().
def main():
    running = True
    # the game loop
    while running:
        ...
        
        # draw
        ...

        # update
        sprites_group.update()
        pygame.display.flip()
If we run the program and move the player:
Player movement is so fast. It's about FPS. FPS stands for frame per second. I'm not touching this concept in this post. To sum up, our game is frame-based game and FPS is depending on computer speed currently. We are able to get over this problem with tick() for a while. We will give an argument as an integer, for instance, if we pass 60 to tick function, that means every second just show 60 frames on the screen. So, we are creating our clock object for using time that is a module of pygame. It gives info about in-game time:
 ...
# we initialize pygame module
pygame.init()

clock = pygame.time.Clock()

...
Finally, we are adding clock.tick(60) statement in the game loop:
...

def main():
    running = True
    # the game loop
    while running:
        clock.tick(60)

        ...
As a result:

Player Movement



No comments:

Post a Comment