gpt4 book ai didi

python - python中的归一化和垂直函数

转载 作者:行者123 更新时间:2023-11-28 19:33:28 26 4
gpt4 key购买 nike

我正在经历一个 blog 在 2D 游戏中创建闪电效果。我想在 python 中实现相同的效果。但是我被困在一个地方。

假设 startpointendPoint 是二维平面中的坐标,代表线段的极值点。

让我们看看博客中的以下代码片段:

midPoint = Average(startpoint, endPoint);
// Offset the midpoint by a random amount along the normal.
midPoint += Perpendicular(Normalize(endPoint-startPoint))*RandomFloat(-offsetAmount,offsetAmount);

.


Normalize(endPoint-startPoint):

那条线得到一个从startPoint到endPoint的单位向量(长度为1的向量)


Perpendicular(Normalize(endPoint-startPoint))

然后得到一个垂直于它的向量(即与直线成直角)


我不是一个普通的 python 程序员。 python 中是否有任何内置的 NormalisePerpendicular 函数可以帮助我在 python 中实现上述代码。

最佳答案

我不知道内置或第三方方法,但它们非常简单:

import numpy as np

def perpendicular( a ) :
b = np.empty_like(a)
b[0] = -a[1]
b[1] = a[0]
return b

def normalize(a):
a = np.array(a)
return a/np.linalg.norm(a)

if __name__ == "__main__":
a = [1,2]
print perpendicular(normalize(a))
b = (4,-6)
print perpendicular(normalize(b))

这将打印

[-0.89442719  0.4472136 ]
[ 0.83205029 0.5547002 ]

你可以调用这些函数

  • 二元组
  • 长度为2的列表
  • 长度为 2 的一维数组

或类似类型。

请注意,如果向量 a 的长度为零,normalize 将引发异常。

我决定根据 PEP 8,Python 风格指南将我的函数命名为小写。

关于python - python中的归一化和垂直函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16890711/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com