简体   繁体   中英

PyGame Random Movement utilizing Pygame.math.vector2d() Crashing

Hey I need some help debugging why my code is crashing. I am fairly new to Python and Pygame and simply wanted to learn in my free time. I watched some physics tutorials in Pygame online and tried to create a simple game window where circles move randomly with no collisions. Here is my code where I believe the issue is:

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')

And here is the class :

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

Any help would be appreciated! Otherwise I will simply follow a different process to create random movement. Thanks!

The application crashes when the length of the vector is 0. The normalize() method computes a Unit vector . Therefore, the components of the vector are divided by the Euclidean length of the vector. If the length of the vector is 0, this causes division by 0.
Even more, you are using the operation incorrectly. normalize does not change the vector itself, but returns a new vector with the same direction but length 1. In compare normalize_ip normalizes the vector in place so that its length is 1.

Use normalize_ip and test that at least 1 of the vector components is not 0:

class Ball:
    # [...]

    def get_random_velocity():
        # [...]

       if new_vector.x != 0 or new_vector.y != 0:
           new_vector.normalize_ip()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM