微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决如何让我随机移动的对象在 pygame 中以特定角度移动

Full Code

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 中构建一个蚂蚁模拟器。蚂蚁从中间开始,然后从那里随机移动。运动是这样工作的。每隔几毫秒 self.new_line 设置为 True。然后计算新的 self.deltaxself.deltay。现在,只要 self.new_line 为 False,我的蚂蚁每次迭代都会以 self.x += deltaxself.y += deltay 移动。当 self.new_line 再次为 True 时,蚂蚁会用新的 self.deltaxself.deltay 值开始一个新行。 deltax 和 deltay 的值介于 -2 和 +2 之间,这意味着蚂蚁可以向各个角度移动。

Visualization

问题:

  1. 但是我希望我的蚂蚁只以特定角度移动。 Like This

我该怎么做?

  1. 如果你用 on ant 运行程序,你会看到蚂蚁的速度随着换行而改变。如何让我的蚂蚁有一个一致的速度?

  2. 如何让我的蚂蚁以特定角度在墙壁上弹跳?

感谢您的帮助。

解决方法

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

# the 2d array
arr = np.ones((5,5))

# a manually way to stack the array 3 times along a new axis
arr3d1 = np.array([arr for i in range(3)])

# even more manually (without stacked loops though)
# useful if you want to change the content eg:
arr3d2 = np.array([arr,1/arr,2*arr])

# use numpy's tile 
arr_h=arr[None,:,:] # first prepend a new singular axis
arr3d3 = np.tile(arr_h,(3,1,1)) # repeat 3 times along first axis and keep other axes

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。