[英]How can i make my randomly moving object move in a specific angle in pygame
self.VEL = 3
self.RAND = numpy.linspace(-self.VEL, +self.VEL, 100) # calculating value between -2 and 2, a total of 100 values
-----------------------------------------
if self.new_line:
self.deltax = random.choice(self.RAND)
self.deltay = random.choice(self.RAND)
self.new_line = False
self.move(self.deltax, self.deltay)
-----------------------------------------
def move(self, deltax, deltay):
self.x += deltax
self.y += deltay
我目前正在使用 pygame 在 python 中构建 ant 模拟器。 蚂蚁从中间开始,然后从那里随机移动。 运动是这样进行的。 每隔几毫秒self.new_line
设置为 True。 然后计算一个新的self.deltax
和self.deltay
。 现在,只要self.new_line
为 False,我的 ant 就会随着self.x += deltax
和self.y += deltay
每次迭代移动。 当self.new_line
再次为 True 时, ant 将使用self.deltax
和self.deltay
的新值开始一个新行。 deltax 和 deltay 的值介于 -2 和 +2 之间,这意味着 ant 可以在各个角度移动。
问题:
我怎样才能做到这一点?
如果您在 ant 上运行程序,您将看到 ant 的速度随着新行的变化而变化。 如何让我的 ant 有一个一致的速度?
如何让我的 ant 以特定角度反弹墙壁?
谢谢你的帮助。
这是多个问题。 目的是只问一个问题。 我只会回答其中的2个。
使用pygame.math.Vector2
和rotate()
生成在指定范围内具有恒定长度和角度的方向向量:
if self.new_line:
angle = random.randint(-45, 45)
direction_vector = pygame.math.Vector2(0, -self.VEL).rotate(angle)
self.deltax = direction_vector.x
self.deltay = direction_vector.y
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.