Jump to content
  • Advertisement
Sign in to follow this  

Smooth movement of player in pygame

This topic is 2928 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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

for event in pygame.event.get()

nextPos = currentPos

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

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

#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.

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
Sign in to follow this  

  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!