繁体   English   中英

如何让我随机移动的 object 在 pygame 中以特定角度移动

[英]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.deltaxself.deltay 现在,只要self.new_line为 False,我的 ant 就会随着self.x += deltaxself.y += deltay每次迭代移动。 self.new_line再次为 True 时, ant 将使用self.deltaxself.deltay的新值开始一个新行。 deltax 和 deltay 的值介于 -2 和 +2 之间,这意味着 ant 可以在各个角度移动。

可视化

问题:

  1. 但是我希望我的蚂蚁只以特定的角度移动。 像这样

我怎样才能做到这一点?

  1. 如果您在 ant 上运行程序,您将看到 ant 的速度随着新行的变化而变化。 如何让我的 ant 有一个一致的速度?

  2. 如何让我的 ant 以特定角度反弹墙壁?

谢谢你的帮助。

这是多个问题。 目的是只问一个问题。 我只会回答其中的2个。
使用pygame.math.Vector2rotate()生成在指定范围内具有恒定长度和角度的方向向量:

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.

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