Moving an object in PyGame Python (original) (raw)
Last Updated : 12 Jul, 2025
To make a game or animation in Python using PyGame, moving an object on the screen is one of the first things to learn. We will see how to move an object such that it moves **horizontally when pressing the right arrow key or left arrow key on the keyboard and it moves **vertically when pressing up arrow key or down arrow key. We’ll create a game window, draw an object and update its position based on user input.
**Change in Co-ordinates for respective keys pressed:
**Left arrow key: Decrement in x co-ordinate
**Right arrow key: Increment in x co-ordinate
**Up arrow key: Decrement in y co-ordinate
**Down arrow key: Increment in y co-ordinate
Setting Up PyGame
Before starting, make sure PyGame is installed. We can install it using:
pip install pygame
Example: Moving a Rectangle
In this code, we create a window using PyGame and draw a rectangle on the screen. The rectangle can be moved using the arrow keys and its position updates as we press the keys. This helps in learning how to handle movement and user input in PyGame.
Python `
import pygame pygame.init()
win = pygame.display.set_mode((500, 500)) pygame.display.set_caption("Moving rectangle")
x = 200 y = 200
width = 20 height = 20
vel = 10 run = True
infinite loop
while run: pygame.time.delay(10)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] and x>0:
x -= vel
if keys[pygame.K_RIGHT] and x<500-width:
x += vel
if keys[pygame.K_UP] and y>0:
y -= vel
if keys[pygame.K_DOWN] and y<500-height:
y += vel
win.fill((0, 0, 0))
pygame.draw.rect(win, (255, 0, 0), (x, y, width, height))
pygame.display.update() pygame.quit()
`
**Output
**Explanation: This code -
- Imports and initializes **Pygame to use its features.
- Creates a 500x500 game window and sets the title.
- Defines rectangle position ****(x, y)**, size and speed.
- Runs a loop to keep the window active until closed.
- Uses **pygame.event.get() to detect the quit event.
- Uses **pygame.key.get_pressed() to detect arrow key presses.
- Updates the rectangle’s position based on key input.
- Clears the screen and redraws the rectangle every frame.
- Refreshes the display using **pygame.display.update().
- Exits Pygame when the loop ends.