我的 pygame 模块有问题。我有一个小程序,用户可以单击窗口中的任何位置,一个球将在那里生成,并开始以 45 度角(实际上是 135 度)向左移动,一切看起来都很好,但如果你生成许多这样的球体,那么它们像光束一样移动,您会发现它们实际上并不是每次都反射 90 度。我的意思是,反射不是随机的,而是经过计算的,但 45 度的方向显然比应有的更接近 90 度。如果您启动该程序,您就会明白我的意思。所以这是代码:
import math
import pygame
NE = 45
NW = 135
SW = 225
SE = 315
V = 5
TICK = 60
RADIUS = 10
def convert_degrees_to_radians(angle_degrees):
return math.radians(angle_degrees)
class Circle:
def __init__(self, center_pos, direction_angle):
self.center_pos = center_pos
self.movement_angle, self.movement_direction = None, None
self.change_direction(direction_angle)
def change_direction(self, new_angle):
self.movement_angle = new_angle
self.movement_direction = pygame.math.Vector2(math.cos(convert_degrees_to_radians(new_angle)),
math.sin(convert_degrees_to_radians(new_angle)))
def change_position(self, new_position):
self.center_pos = new_position
def draw_circle(position):
pygame.draw.circle(screen, pygame.Color('white'), position, RADIUS)
if __name__ == '__main__':
pygame.init()
pygame.display.set_caption('Balls')
size = width, height = 1000, 600
screen = pygame.display.set_mode(size)
running = True
circles = []
clock = pygame.time.Clock()
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.MOUSEBUTTONUP and event.button == 1:
draw_circle(event.pos)
circles.append(Circle(event.pos, NW))
screen.fill(pygame.Color('black'))
clock.tick(TICK)
for circle in circles:
new_center_pos = [int(circle.center_pos[0] + V * circle.movement_direction.x),
int(circle.center_pos[1] - V * circle.movement_direction.y)]
circle.change_position(tuple(new_center_pos))
draw_circle(circle.center_pos)
if circle.center_pos[0] <= RADIUS:
if circle.movement_angle == SW:
circle.change_direction(SE)
if circle.movement_angle == NW:
circle.change_direction(NE)
if circle.center_pos[0] >= width - RADIUS:
if circle.movement_angle == SE:
circle.change_direction(SW)
if circle.movement_angle == NE:
circle.change_direction(NW)
if circle.center_pos[1] <= RADIUS:
if circle.movement_angle == NW:
circle.change_direction(SW)
if circle.movement_angle == NE:
circle.change_direction(SE)
if circle.center_pos[1] >= height - RADIUS:
if circle.movement_angle == SW:
circle.change_direction(NW)
if circle.movement_angle == SE:
circle.change_direction(NE)
pygame.display.flip()
pygame.quit()
有人知道如何解决这个问题吗?我试过了,但确实看不出有什么错误。
我尝试自己计算方向而不是使用度数,但结果是相同的,所以也许new_center_pos的计算有问题,但我看不到它。
问题就在这里:
new_center_pos = [int(circle.center_pos[0] + V * circle.movement_direction.x), int(circle.center_pos[1] - V * circle.movement_direction.y)]
您可以使用浮点坐标正确计算所有内容,但不幸的是您在将坐标分配给新位置之前将坐标转换为
int
。由于新的位置用于下一帧的计算,因此运动不准确。
请勿转换为
int
new_center_pos = [circle.center_pos[0] + V * circle.movement_direction.x,
circle.center_pos[1] - V * circle.movement_direction.y]
round
仅画圆的位置
pygame.draw.circle(screen, pygame.Color('white'), (round(position[0]), round(position[1])), RADIUS)