2017-04-02 73 views
1

我試圖在pygame中繪製一個振盪的矩形。math.pi在pygame中沒有像預期的那樣工作

當我使用

particle.pos[0] = 100 * math.sin(188.5 * t) + screen_width/2 

它的作品,因爲我希望它,但是當我使用

omega = 2*math.pi*fps 
particle.pos[0] = 100 * math.sin(omega * t) + screen_width/2 

的繪製矩形,但不動。我已經證實歐米茄約爲188.5,歐米茄和188.5都是漂浮物。我唯一能想到的就是math.pi會以某種方式導致問題,但我不知道爲什麼。

編輯: 整個事情

import sys 
import math 
import pygame 
from pygame.locals import * 

pygame.init() 

BLACK = (0, 0, 0) 
WHITE = (255, 255, 255) 
RED = (255, 0, 0) 
GREEN = (0, 255, 0) 
BLUE = (0, 0, 255) 

fps = 30 
fpsClock = pygame.time.Clock() 

screen_width, screen_height = 640, 480 
screen = pygame.display.set_mode((screen_width, screen_height)) 


class Particle: 
    """Particle""" 
    def __init__(self, size, pos, particlecolor): 
     self.size = size 
     self.pos = pos 
     self.particlecolor = particlecolor 

    def draw(self): 
     pygame.draw.rect(screen, GREEN, [self.pos, self.size]) 

particle = Particle([10, 10], [screen_width * .25, screen_height * .5], GREEN) 

t = 0 
omega = 2*math.pi*fps 

while True: 
    t += 1 
    screen.fill(BLACK) 

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

    particle.pos[0] = 100 * math.sin(omega * t) + screen_width/2 
    # particle.pos[0] = 100 * math.sin(188.5 * t) + screen_width/2 

    particle.draw() 

    pygame.display.flip() 
fpsClock.tick(fps) 
+1

[更多代碼請](http://stackoverflow.com/help/mcve)。 – skrx

+0

@skrx添加代碼 – user44557

+0

考慮到當't'爲0時,結果爲320,'t'爲100時爲'319.9999999997962',我並不感到驚訝,當你在時間。 – zondo

回答

2

的問題是,您使用的2個* math.pi弧度倍數爲你的角度(這將是360°(一個完整的圓)),所以你得到幾乎表達式100 * math.sin(omega * t) + screen_width/2的結果相同。

print 100 * math.sin(omega * t) + screen_width/2 

輸出:

319.99999999999784 
319.9999999999957 
319.99999999998784 
319.99999999999136 
319.9999999999949 
319.99999999997567 
319.99999999997925 

嘗試omega = 0.1弧度得到一個不錯的結果。

相關問題