Skip to main content
 首页 » 编程设计

python之有没有一种方法可以减少pygame的更新

2024年11月24日8mq0036

我的pygame运行速度太快了。当我在广场上施力时,它会立即消失。

我尝试使用较小的数字,但似乎无法使其稳定运行。

screen = pg.display.set_mode((640, 480)) 
 
x, y = 200, 200 
 
xvel, yvel = 0, 0 
 
xaccel, yaccel = 0, 0 
 
def update_rect(): 
    global x, y, xvel, yvel, xaccel, yaccel 
    x += xvel 
    y += yvel 
 
    xvel += xaccel 
    yvel += yaccel 
 
    xaccel, yaccel = 0, 0 
 
def apply_force(fx, fy): 
    global xaccel, yaccel 
    xaccel += fx 
    yaccel += fy 
 
while True: 
    screen.fill((0, 0, 0)) 
    pg.draw.rect(screen, (255, 255, 255), (x, y, 40, 40), 0) 
 
    pg.display.update() 
    update_rect() 
    apply_force(0, 0.1) 
 
 
 
    handle_keys() 


我的预期结果是矩形将缓慢从屏幕上掉落,但立即消失。

请您参考如下方法:

您应该使用时钟来减慢while循环。为此,您可以轻松创建pygame.time.Clock实例,并在while循环中使用tick(FPS)方法。勾号方法采用一个值作为您想要的FPS。

import pygame as pg 
 
screen = pg.display.set_mode((640, 480)) 
 
x, y = 200, 200 
 
xvel, yvel = 0, 0 
 
xaccel, yaccel = 0, 0 
 
clock = pg.time.Clock() # created the clock here. 
 
def update_rect(): 
    global x, y, xvel, yvel, xaccel, yaccel 
    x += xvel 
    y += yvel 
 
    xvel += xaccel 
    yvel += yaccel 
 
    xaccel, yaccel = 0, 0 
 
def apply_force(fx, fy): 
    global xaccel, yaccel 
    xaccel += fx 
    yaccel += fy 
 
while True: 
    screen.fill((0, 0, 0)) 
    pg.draw.rect(screen, (255, 255, 255), (x, y, 40, 40), 0) 
 
    pg.display.update() 
    update_rect() 
    apply_force(0, 0.1) 
 
    for event in pg.event.get(): 
        if event.type == pg.QUIT: 
            pg.quit() 
            quit() 
 
    clock.tick(30) # you can change the value as you wish.