在pygame中上下移动矩形的问题

问题描述

我尝试使用箭头键在 Pygame 中移动一个矩形。我可以左右移动它,但它不能上下移动。如果我按下向下键,它会在 y 方向上增长而不是移动。 这是代码

    import pygame,sys
    from pygame.locals import *

    catx = 10
    caty = 10
    screen =0

    def myquit():
        pygame.quit()
        sys.exit()
    
    def event_input(events):
        global catx,caty,screen
    
        for event in events:
            if event.type == QUIT:
                pygame.quit()
            else:
                if event.type== KEYDOWN:
                    if event.key== K_ESCAPE:
                        myquit()
                    elif event.key== K_RIGHT:
                        catx+=5
                    elif event.key==K_LEFT:
                        catx-=5
                    else:
                        pass
                elif event.type== KEYUP:
                    if event.key== K_DOWN:
                        caty+=5
                    elif event.key== K_UP:
                        caty-=5
                screen.fill((0,0))
                pygame.draw.rect(screen,(255,255,255),(catx,50,caty))
                pygame.display.update()
    
    
    def main():
        global screen
        pygame.init()
        screen_width=640
        screen_height=500
        pygame.display.set_mode((screen_width,screen_height))
        pygame.display.set_caption("Move Rectangle")
        screen = pygame.display.get_surface()
        pygame.display.update()
    
        while True:
            event_input(pygame.event.get())
    
    main()

解决方法

您正在更改矩形的高度而不是位置。 pygame.rect 的参数是 (x,y,width,height),但是你的参数被传递,好像参数是(x,height,y),所以它改变了矩形的高度而不是 y。换行

pygame.draw.rect(screen,(255,255,255),(catx,50,caty))

pygame.draw.rect(screen,caty,50))