All*_*len 1 python numpy scipy
我的游戏窗口大小为 640 x 480,它由粒子填充,但是当粒子离开一侧时,它会环绕到另一侧(即,它是一个环形线圈)。
我想计算每个粒子之间的距离,因为这将用于向每个粒子施加不同的力。
起初,我循环遍历每对粒子,然后重新调整所有内容,使成对的第一个粒子居中,然后计算到第二个粒子的距离,但这运行速度非常慢。
然后我发现 scipy.spatial.distance 中的一些函数可以让我非常快速地计算所有点之间的距离,但唯一的问题是它没有考虑环绕。
这是我当前的代码
from scipy.spatial.distance import pdist, squareform
...
distance = squareform(pdist([(p.x, p.y) for p in particles]))
Run Code Online (Sandbox Code Playgroud)
这适用于中心附近的粒子,但如果一个粒子位于 (1, 320),另一个粒子位于 (639, 320),那么它会将它们的距离计算为 638,而不是 2。它不考虑裹。
我可以使用不同的函数,或者我可以在考虑换行之前/之后应用一些转换吗?
您可以计算 x 和 y 差异(窗口内差异与边缘交叉距离)中较小的一个,如下所示:
game_width = 640
game_height = 480
def smaller_xy(point1, point2):
xdiff = abs(point1.x - point2.x)
if xdiff > (game_width / 2):
xdiff = game_width - xdiff
ydiff = abs(point1.y - point2.y)
if ydiff > (game_height / 2):
ydiff = game_height - ydiff
return xdiff, ydiff
Run Code Online (Sandbox Code Playgroud)
也就是说,如果 x 或 y 方向上的窗口内距离大于该方向上窗口大小的一半,则最好离开边缘 - 在这种情况下,该距离将是该方向上的窗口大小方向减去原来的窗内距离。
显然,一旦获得 x 和 y 间隔,您就可以计算点之间的距离:
import math
small_x, small_y = smaller_xy(p1, p2)
least_distance = math.sqrt(small_x**2 + small_y**2)
Run Code Online (Sandbox Code Playgroud)
但是,根据力计算的定义方式,您可能会发现您真正需要的只是距离的平方(只需 ( small_x**2 + small_y**2)),因此您可以避免查找 的工作sqrt。
要深入了解scipy.pdist,请注意,pdist除了点之外,还可以使用函数参数来调用 ,如下所示:
Y = pdist(X, func)
Run Code Online (Sandbox Code Playgroud)
这是https://docs.scipy.org/doc/scipy/reference/ generated/scipy.spatial.distance.pdist.html#scipy.spatial.distance.pdist 的描述中显示的最后一种调用pdist形式
您应该能够使用该功能来pdist根据应用计算的回调函数计算的距离来构建其所有点对之间的距离矩阵smaller_xy。
| 归档时间: |
|
| 查看次数: |
1322 次 |
| 最近记录: |