math.pi在pygame中没有按预期工作

时间:2017-04-02 01:54:17

标签: python pygame

我正试图在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 个答案:

答案 0 :(得分: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弧度以获得不错的结果。