Pygame 玩家移动很奇怪

Pygame player movement is being weird

我正在做一个 pygame 项目,我做了一个方块移动,它会在每一帧召唤一个方块,并且只有一行方块。

我试着每帧都更新屏幕(因为我还没有),但这没有用。这是我的代码:

#Import Pygame
import pygame

#screen object(width, height)

screen_x = 750
screen_y = 600
screen = pygame.display.set_mode((screen_x, screen_y))

#Set the caption of the screen

pygame.display.set_caption('Game')

#Define a velocity, x, and y variable
velocity = 2.5x = 0.0y = 0.0

#Variable to keep our game loop running

running = True

#Game loop

while running:

   # Initialing Color
   color = (255,0,0)

    if pygame.key.get_pressed()[pygame.K_w]:
        y += 2.5

    if pygame.key.get_pressed()[pygame.K_s]:
        y -= 2.5 


    if pygame.key.get_pressed()[pygame.K_a]:
        x -= 2.5 


    if pygame.key.get_pressed()[pygame.K_d]:
        x += 2.5 

# Drawing Rectangle
pygame.draw.rect(screen, color, pygame.Rect(x, y, 50, 50))
pygame.display.flip()
pygame.display.update()
# for loop through the event queue
for event in pygame.event.get():
    # Check for QUIT event  
    if event.type == pygame.QUIT:
            running = False

整个场景每一帧都重绘,所以你必须每一帧都清空显示:

import pygame

#screen object(width, height)
screen_x = 750
screen_y = 600
screen = pygame.display.set_mode((screen_x, screen_y))

#Set the caption of the screen
pygame.display.set_caption('Game')

#Define a velocity, x, and y variable
velocity = 2.5
x, y = 0, 0
color = (255,0,0)

clock = pygame.time.Clock()
running = True
while running:
    clock.tick(100)
    # for loop through the event queue
    for event in pygame.event.get():
        # Check for QUIT event  
        if event.type == pygame.QUIT:
                running = False

    keys = pygame.key.get_pressed()   
    x += (keys[pygame.K_d] - keys[pygame.K_a]) * velocity
    y += (keys[pygame.K_s] - keys[pygame.K_w]) * velocity

    # clear display
    screen.fill((0, 0, 0)) 

    # Drawing Rectangle               
    pygame.draw.rect(screen, color, pygame.Rect(x, y, 50, 50))

    # update display
    pygame.display.flip()

pygame.quit()
exit()

典型的 PyGame 应用程序循环必须:

解决方法很简单。你忘了用颜色填充屏幕。因为您的代码只是在每一帧都在屏幕表面绘制一个正方形,这就是它绘制一行正方形的原因。你必须在画东西之前填满屏幕,否则你会看到一个空白的屏幕,屏幕上有你填充表面的那种颜色。希望对你有帮助。