2017-10-28 65 views
1

Pygame模塊中的形狀不能把浮點值作爲它們的參數嗎?Pygame形狀不能帶非整數參數

這是由於我目前正在做一個相對基本的物理模擬,並使用pygame來完成圖形這一事實而引發的,在物理模擬中,它很少/從不發生一個對象居中的情況,一個整數值。

我想知道這主要是否會對模擬的準確性有重大影響?

+0

我通常保存我的對象在['pygame.math.Vector2's]的實際位置(http://www.pygame.org/docs/ref/math.html#pygame.math.Vector2 ),因爲'pygame.Rect'不能存儲浮點數並導致不準確的運動。您可以將Vector2傳遞給'pygame.Surface.blit'或將其分配給矩形,但是如果您想將其用於例如'pygame.draw.circle',則必須先將矢量轉換爲整數。 – skrx

+0

我只使用Pygame來製作圖形,因爲我想了解制作(矢量和普通)類並將它們實現到引擎中的過程。因此,如果我只是將數值四捨五入到最接近的整數,那麼在顯示對象時,使用精確值進行進一步計算時,這足夠準確嗎?我的推理是因爲這些形狀的參數是它們的像素位置,所以在顯示時,如果它最多偏離0.5 px,那麼應該沒有那麼重要了。 – Bob

+0

是的,應該是準確的。只要實際位置準確,如果對象顯示爲向左或向右進一步0.5像素,則不會影響仿真。你甚至不需要自己將數字舍入,因爲當你將它們傳遞給'.blit'或者將它們賦值給一個矩形時,pygame自動爲你做這些。只有像'pygame.draw.circle'這樣的函數不接受浮點數。 – skrx

回答

0

以仿真術語/準確性來說,您應始終保持數據爲浮點型。你應該圍繞它們,在你調用Pygame需要整數的函數的時候將它們轉換爲int。

就做這樣的事情:

pygame.draw.rect(surface, color, (int(x), int(y), width, height)) 

繪製一個矩形,例如。

0

我通常建議將遊戲對象的位置和速度存儲爲vectors(其中包含浮點數)以保持物理準確。然後,您可以首先將速度添加到位置矢量,然後更新用作blit位置的對象的矩形,並可用於碰撞檢測。在將它分配給矩形之前,您不必將位置向量轉換爲整數,因爲pygame會自動爲您執行此操作。

下面是一個跟隨鼠標的對象的小例子。

import pygame as pg 
from pygame.math import Vector2 


class Player(pg.sprite.Sprite): 

    def __init__(self, pos, *groups): 
     super().__init__(*groups) 
     self.image = pg.Surface((30, 30)) 
     self.image.fill(pg.Color('steelblue2')) 
     self.rect = self.image.get_rect(center=pos) 
     self.direction = Vector2(1, 0) 
     self.pos = Vector2(pos) 

    def update(self): 
     radius, angle = (pg.mouse.get_pos() - self.pos).as_polar() 
     self.velocity = self.direction.rotate(angle) * 3 
     # Add the velocity to the pos vector and then update the 
     # rect to move the sprite. 
     self.pos += self.velocity 
     self.rect.center = self.pos 


def main(): 
    screen = pg.display.set_mode((640, 480)) 
    clock = pg.time.Clock() 
    font = pg.font.Font(None, 30) 
    color = pg.Color('steelblue2') 
    all_sprites = pg.sprite.Group() 
    player = Player((100, 300), all_sprites) 

    done = False 

    while not done: 
     for event in pg.event.get(): 
      if event.type == pg.QUIT: 
       done = True 

     all_sprites.update() 
     screen.fill((30, 30, 30)) 
     all_sprites.draw(screen) 
     txt = font.render(str(player.pos), True, color) 
     screen.blit(txt, (30, 30)) 

     pg.display.flip() 
     clock.tick(30) 


if __name__ == '__main__': 
    pg.init() 
    main() 
    pg.quit()