2
\$\begingroup\$

Thanks for taking the time to read this. Right now I'm making a really basic tile based game. The map is a large amount of 16x16 tiles, and the character image is 16x16 as well. My character has its own class that is an extension of the sprite class, and the x and y position is saved in terms of the tile position.

To note I am fairly new to pygame.

My question is, I am planning to have character movement restricted to one tile at a time, and I'm not sure how to make it so that, even if the player hits the directional key dozens of time quickly, (WASD or arrow keys) it will only move from tile to tile at a certain speed. How could I implement this generally with pygame? (Similar to game movement of like Pokemon or NexusTk).

Edit: I should probably note that I want it so that the player can only end a movement in a tile. He couldn't stop moving halfway inbetween a tile for example.

Thanks for your time! Ryan

\$\endgroup\$
1
  • \$\begingroup\$ YOUR QUESTION SAVED MY LIFE!! THAAAAANK YOU!!! \$\endgroup\$ Commented May 25, 2014 at 2:31

1 Answer 1

2
\$\begingroup\$

Basically what you are probably looking for is a little timer which counts down the time until the next move is possible after a move was done. Like so (not tested, replace w_key_pressed etc by the proper input checks):

walk_cooldown = 0
WALK_DELAY = 1 # the time between 2 steps

clock = pygame.time.Clock()
while(true): # this is your MAIN LOOP, you can put some of this stuff into your player class
    delta = clock.tick() / 1000.0

    walk_cooldown -= delta

    if walk_cooldown <= 0:
        if(w_key_pressed): 
            walk_down_one_tile()
            walk_cooldown = WALK_DELAY
        if(s_key_pressed): 
            walk_down_one_tile()
            walk_cooldown = WALK_DELAY
        # ... the usual stuff, however you do it

Notice how walk_cooldown is set to WALK_DELAY when you move, and is being decreased by the time passed each frame. You can only move, when walk_cooldown is less than or equal to 0.

\$\endgroup\$
2
  • \$\begingroup\$ Oh I see! My one question is, since I have a clock.tick(30) call at the end of my game loop for FPS, and click.tick() also returns the time since the last call, would this be screwed up by also calling it at the beginning of the game loop? I'm not sure how to organize it all. \$\endgroup\$
    – Ryan
    Commented Nov 10, 2012 at 23:49
  • \$\begingroup\$ Usually you do the main loop in this order: Timing Input Simulation / Updating Rendering. So move your clock.tick(30) to the beginning and it should work fine. \$\endgroup\$
    – opatut
    Commented Nov 11, 2012 at 0:37

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .