Arrow Key Movement in Pygame

Question:

I am starting with pygame and can’t seem to figure out how to implement continuous movement. This is my current code:

import pygame

pygame.init()
window = pygame.display.set_mode(((500, 500)))
pygame.display.set_caption(("First Game"))

x = 50
y = 50
width = 40
height = 60
vel = 10

run = True
while run:
    pygame.time.delay(100)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT]:
        x -= vel
    if keys[pygame.K_RIGHT]:
        x += vel
    if keys[pygame.K_UP]:
        y -= vel
    if keys[pygame.K_DOWN]:
        y += vel

    window.fill((0, 0, 0))
    pygame.draw.rect(window, (200, 23, 255), (350, 350, width, height))
    pygame.display.update()
   
pygame.quit()

As I have just started, I can’t think of any possible solutions. Would be really nice of you if you can resolve this issue of mine. I know there is going to be some really stupid bug.

Asked By: Anay Garodia

||

Answers:

Draw your rectangle at x and y coordinates as origin.

Answered By: Gea

You need to draw the rectangle x, y instead of constant 350, 350:

pygame.draw.rect(window, (200, 23, 255), (350, 350, width, height))

pygame.draw.rect(window, (200, 23, 255), (x, y, width, height))

For a smooth movement you need to set vel to 1 and decrease the delay in the application loop.
Use pygame.time.Clock to control the frames per second and thus the game speed.

The method tick() of a pygame.time.Clock object, delays the game in that way, that every iteration of the loop consumes the same period of time. See pygame.time.Clock.tick():

import pygame

pygame.init()
window = pygame.display.set_mode(((500, 500)))
pygame.display.set_caption(("First Game"))

x, y = 50, 50
width, height = 40, 60
vel = 1

clock = pygame.time.Clock()
run = True
while run:
    clock.tick(100)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT]:
        x -= vel
    if keys[pygame.K_RIGHT]:
        x += vel
    if keys[pygame.K_UP]:
        y -= vel
    if keys[pygame.K_DOWN]:
        y += vel

    window.fill((0, 0, 0))
    pygame.draw.rect(window, (200, 23, 255), (x, y, width, height))
    pygame.display.update()
   
pygame.quit()
Answered By: Rabbid76

For each key press, add the following code x_vel += vel or y_vel += vel. Then use

x += x_vel
y += y_vel

x_vel *= .9
y_vel *= .9

And then adjust the values accordingly. You could porobably make a variable called friction that holds the value that you multiply x_vel and y_vel by.

Answered By: Emlore
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.