Sign in to follow this  
kvsingh

Smooth movement of player in pygame

Recommended Posts

I'm using the pygame library. The following is pseudo code for my event handling for the player.



#generates multiple events for keys that are held down
pygame.key.set_repeat(30,30)

for event in pygame.event.get()

nextPos = currentPos

if(keyUp):
if event.key == w :
key_w = false
#do the same for s, a and d

if(keyDown):
if event.key == w:
key_w = true
#same for s,a and d

if(key_w):
#update nextPos

#do same for key_s, key_a and key_d

currentPos = nextPos






The problem is that sometimes when i move my mouse on the screen, and i'm pressing a key at the same time, while processing the events of the mouse, the events of the key are queued up, and these multiple keypresses are executed together, so that the player seems to jump a huge distance.

This problem is not caused if i don't move the mouse at all.

Share this post


Link to post
Share on other sites
That's because you're executing the movement code every time an event is handled. Don't do that. Instead, handle the events first, and then, outside that loop, run the movement code once. Keep in mind that Python uses indentation to indicate scope.

Example:
while gameIsRunning:
# 1. Handle events:
for event in pygame.event.get():
# alter velocity based on key events/state

# 2. Update game logic:
position = position + velocity

# 3. Draw stuff to screen

You may want to take the time delta into account when moving (move less when less time has elapsed since the last update). Alternately, you could go for a fixed update interval.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this