[英]PyGame Random Movement utilizing Pygame.math.vector2d() Crashing
嘿,我需要一些帮助来调试我的代码崩溃的原因。 我对 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
任何帮助,将不胜感激! 否则,我将简单地遵循不同的过程来创建随机运动。 谢谢!
当向量的长度为 0 时,应用程序崩溃。 normalize()
方法计算单位向量。 因此,向量的分量除以向量的欧几里得长度。 如果向量的长度为 0,则会导致除以 0。
更重要的是,您使用的操作不正确。 normalize
不会改变向量本身,而是返回一个具有相同方向但长度为 1 的新向量。在 compare normalize_ip 中对向量进行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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.