[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]

Re: [pygame] keep a key pressed and then move a sprite



On 2010.11.24 12:27 PM, Ian Mallett wrote:
Hi,

Try this:

The PyGame event manager fires events /only when a key's state changes
/(that is, the moment it is pressed or the moment it was released, a
/single /event is fired).

What you want to do is to check the /current state /of the keyboard.
"pygame.key.get_pressed()" does this.  The state "key" that it returns
can then be checked for the required key.

That's all correct. One other option (though get_pressed is probably better) is to watch for both the KEYDOWN and KEYUP events. You could start the characters moving on a KEYDOWN event and keep moving them until there's a KEYUP event.

Constants like K_LEFT are defined in pygame.locals, so you can either reference them like "pygame.locals.K_LEFT" or (easier) say "from pygame.locals import *" so you can just say "K_LEFT".

Also, consider separating the code for what happens to the character/sprite from the bit that reacts to keyboard input. I try to do something like:
"if keys[K_RIGHT]: player.speed_x = player.speed
if keys[K_UP]: player.speed_y = -player.speed
player.coords[x] += player.speed_x; player.coords[y] += player.speed_y"
That kind of thing lets you separate the movement logic a bit from the way it's inputted.

Note that if you have trouble with certain combinations of keys not registering when pressed together, that's a known problem inherent to keyboards. Google "keyboards are evil" for an explanation.