How To Make A Character Move While Key Is Held Down
Solution 1:
There are two problems with your code. First to your question. The reason the player never moves more than one step is that you reset the player position in every call to draw() when you do
playerx = 20playery = 20
Instead, you should put that code above the draw()
function and add
global playerx
global playery
at the top of draw()
. Now, the player position is not reset every frame.
The second problem is that you create a new screen in every call to draw()
when you do
screen = pygame.display.set_mode((700,300))
pygame.display.set_caption('something')
instead you should move those to lines above draw()
and just use the same screen for every draw.
Also, like elyase points out, what you probably want is to set the velocities to fixed values, not increase them. Like so
velX = 0
velY = 0
if keys_down[K_d]:
velX = 10
if keys_down[K_w]:
velY = -10
if keys_down[K_s]:
velY = 10
if keys_down[K_a]:
velX = -10
This way the player will move around with a constant speed in the direction you steer it.
Hope that clear some stuff up. :)
Solution 2:
You are resetting the position inside draw(). Also you should put the code that changes the direction, inside the event.type == pygame.KEYDOWN
condition. Something like this:
ifevent.type == KEYDOWN:
ifevent.key == K_d:
velX += 50*time
elif event.key == K_w:
velY -= 50*time
...
ifevent.type == KEYUP:
# set velocity to0
Post a Comment for "How To Make A Character Move While Key Is Held Down"