簡體   English   中英

pygame 增量時間導致運動不一致

[英]pygame delta time causes inconsistent movement

我試圖了解增量時間並編寫了這個簡單的示例:

import pygame, sys, time

pygame.init()
screen = pygame.display.set_mode((1280,720))
clock = pygame.time.Clock()

rect1 = pygame.Rect(0,150,100,100)
rect2 = pygame.Rect(1180,500,100,100)
speed = 300

last_time = time.time()

while True:
    dt = time.time() - last_time
    last_time = time.time()

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

    screen.fill('white')
    rect1.x += speed * dt
    rect2.x -= speed * dt

    pygame.draw.rect(screen,'red',rect1)
    pygame.draw.rect(screen,'green',rect2)

    pygame.display.update()
    clock.tick(60)

我遇到的問題是向左移動比向右移動快。 因此,在代碼片段中,綠色矩形 (rect2) 到達屏幕末端的速度明顯快於紅色矩形。

我還嘗試使用 pygame.clock 來獲取增量時間:

import pygame, sys, time

pygame.init()
screen = pygame.display.set_mode((1280,720))
clock = pygame.time.Clock()

rect1 = pygame.Rect(0,150,100,100)
rect2 = pygame.Rect(1180,500,100,100)
speed = 300

while True:

    dt = clock.tick(60) / 1000

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

    screen.fill('white')
    rect1.x += speed * dt
    rect2.x -= speed * dt

    pygame.draw.rect(screen,'red',rect1)
    pygame.draw.rect(screen,'green',rect2)

    pygame.display.update()

但結果還是一樣。

我真的很困惑,我做錯了什么嗎?

編輯:有人關閉了它並鏈接到 deltatime 在更高幀速率下不工作。 這里的幀率是恆定的 60fps。

由於pygame.Rect應該代表屏幕上的一個區域,所以pygame.Rect object 只能存儲整數數據。

Rect 對象的坐標都是整數。 [...]

當 object 的新 position 分配給Rect object 時,坐標的小數部分會丟失。如果每幀都這樣做,position 錯誤將隨着時間累積。

如果要以浮點精度存儲 object 位置,則必須將 object 的位置存儲在單獨的變量中,並且必須同步pygame.Rect object. round入坐標並將其分配給矩形的 position:

rect1 = pygame.Rect(0,150,100,100)
rect2 = pygame.Rect(1180,500,100,100)
pos1_x = rect1.x
pos2_x = rect2.x  
while True:
    # [...]

    pos1_x += speed * dt
    pos2_x -= speed * dt
    rect1.x = round(pos1_x)
    rect2.x = round(pos2_x)
 
    # [...]

另見Pygame 不允許我將 float 用於 rect.move,但我需要它

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM