Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Using Keyboard Arrow Keys
#2
Here's something that hopefully helps. It shows the arrow keys, continuous movement by holding a key down, and smooth movement using an fps clock/delta time, as well as clamping the values so you don't fly off the screen.

import pygame as pg

BLACK = (0, 0, 0)
WHITE = (255, 255, 255)


def main(screen, max_x, max_y):
    x, y = 50, 50
    width, height = 50, 50
    clock = pg.time.Clock()

    x_movement = 0
    delta = 0
    while True:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                return
            if event.type == pg.KEYDOWN:
                # start moving left/right if the keys are pressed
                if event.key == pg.K_LEFT:
                    x_movement = -1
                elif event.key == pg.K_RIGHT:
                    x_movement = 1
            elif event.type == pg.KEYUP:
                # stop movement if the key is un-pressed
                if event.key in [pg.K_LEFT, pg.K_RIGHT]:
                    x_movement = 0

        x += (delta * x_movement)
        # clamp x
        if x <= 0:
            x = 0
        elif x >= max_x - width:
            x = max_x - width

        screen.fill(BLACK)
        pg.draw.rect(screen, WHITE, (x, y, width, height), 0)
        pg.display.update()
        delta = clock.tick(60)


if __name__ == "__main__":
    pg.init()
    width, height = 500, 800
    screen = pg.display.set_mode((width, height))
    main(screen, width, height)
Reply


Messages In This Thread
Using Keyboard Arrow Keys - by rturus - May-25-2021, 11:07 AM
RE: Using Keyboard Arrow Keys - by nilamo - May-25-2021, 04:40 PM
RE: Using Keyboard Arrow Keys - by rturus - May-27-2021, 01:00 PM
RE: Using Keyboard Arrow Keys - by nilamo - May-27-2021, 09:04 PM
RE: Using Keyboard Arrow Keys - by Hanima - Oct-22-2021, 03:20 AM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020