简体   繁体   中英

Can't move a rectangle in pygame

I've been practicing with pygame for a while, and I can't move a rectangle I've drawn.

import pygame
pygame.init()
screen_dimensions=[600,600]
rectx=0
rect=pygame.Rect(rectx,550,50,50)
screen = pygame.display.set_mode(screen_dimensions)
running=True
color = (255, 255, 255)
rect_color=(255,0,0)
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running=False
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_d:
                rectx += 100
    screen.fill(color)
    pygame.draw.rect(screen, rect_color, rect)
    pygame.display.update()

You have to update rect.x rather than rectx

rectx += 100

rect.x += 100

Alternatively, you can update the position of the rectangle after changing rectx :

rectx += 100
rect.x += rectx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM