使用Pygame.math.vector2d()崩溃的PyGame随机运动

时间:2017-02-25 22:46:47

标签: python pygame

嘿,我需要一些帮助来调试我的代码崩溃的原因。我是Python和Pygame的新手,只是想在我的空闲时间学习。我在网上观看了Pygame的一些物理教程,并尝试创建一个简单的游戏窗口,其中圆圈随机移动而不会发生碰撞。这是我的代码,我相信问题是:

for n in range(number_of_circles):
   size = random.randint(10,20)
   x = random.randint(size, screen_width - size)
   y = random.randint(size,screen_height - size)
   color = random.choice(colors)
   velocity = get_random_velocity()
   **my_circle = Ball(pygame.math.Vector2(x,y),size,color,velocity,0)
   my_circles.append(my_circle)**

direction_tick = 0.0

print('failed')

这是班级:

class Ball:
    #the parameters that are already defined are optional.
    #width used to define the fill of the ball.
    #python cannot overload constructors. can only use one
    def __init__(self,position,size,color = (255,255,255),velocity =      pygame.math.Vector2(0,0),width = 1):
    self.position = position
    self.size = size
    self.color = color
    self.velocity = velocity
    self.width = width

    def display(self):
        rx,ry = int(self.position.x),int(self.position.y)
        pygame.draw.circle(screen,self.color,(rx,ry),self.size,self.width)

    def move(self):
        self.position += self.velocity * dtime

    def change_velocity(self,velocity):
        self.velocity = velocity

def get_random_velocity():
    new_angle = random.uniform(0,math.pi*2)
    new_x = math.sin(new_angle)
    new_y = math.cos(new_angle)
    new_vector = pygame.math.Vector2(new_x,new_y)
    new_vector.normalize()
    new_vector *= initial_velocity #pixel movement per second
    return new_vector

任何帮助将不胜感激!否则,我将简单地按照不同的过程来创建随机移动。谢谢!

1 个答案:

答案 0 :(得分:0)

当向量的长度为 0 时,应用程序崩溃。normalize() 方法计算 Unit vector。因此,向量的分量除以向量的 Euclidean length。如果向量的长度为 0,则会导致除以 0。
更重要的是,您使用的操作不正确。 normalize 不会改变向量本身,而是返回一个方向相同但长度为 1 的新向量。在 compare 中,normalize_ip 对向量进行原地归一化,使其长度为 1。

使用 normalize_ip 并测试至少有 1 个向量分量不为 0:

class Ball:
    # [...]

    def get_random_velocity():
        # [...]

       if new_vector.x != 0 or new_vector.y != 0:
           new_vector.normalize_ip()
相关问题