Saturday, December 1, 2012

Timers in Games

I've been trying to figure out the best way to set up timers in games.   Timers are used all the time, for example, the firing rate of a gun, the delay in a joystick button press to check to see how many times the button was pressed, or the speed of an animation.

The overall speed of the game is controlled by a clock that is usually used to control the frame rate.  For  example,
clock = pygame.time.Clock()
framerate = 60
 In the main game loop, the clock is ticked.

 To control time for individual objects, I usually use the standard python time module.

## using the standard python time library, not a pygame module.  
start_time = time.time()
## some action
elapsed_time = time.time() - start_time
## 10 millisecond delay
if elapsed_time > 10:
     ## do the action we've been waiting for.

I notice that many people using the pygame.time module in their games.  I've tried to figure out the advantage of this and I can't understand it out.  The people using this module are usually better programmers than I am.

## using the pygame.time module, not the standard python time library.
current_time = pygame.time.get_ticks()
## example 10 millsecond delayif next_update_time < current_time:    # do stuff    next_update_time = current_time + 10
Finally, I notice that other people are using the main game clock, the one that is usually set to 50 fps or 60 fps.  Here's a code snippet that blits the image once every 10 frames.  If the game is running at 60 frames a second, the image is blitted 6 times a second, effectively setting up a delay of over 100 ms.

class walker:
    def __init__(self):
        self.ani_speed_init = 10
        self.ani_speed = self.ani_speed_init
        self.ani = glob.glob("walk/walk*.png")
        self.ani_pos = 0
        self.ani_max = len(self.ani) - 1
        self.img = pygame.image.load(self.ani[0])
        self.direction = "right"
        self.movement = False
    def update(self, pos):
        self.ani_speed -= 1
        self.x += pos
        if self.ani_speed == 0:
            self.img = pygame.image.load(self.ani[self.ani_pos])
            self.ani_speed = self.ani_speed_init
            if self.ani_pos == self.ani_max:
                self.ani_pos = 0
            elif self.movement:
                self.ani_pos += 1
        if self.direction == "right":
            windowSurface.blit(self.img, (self.x, self.y))

No comments:

Post a Comment