我正在经历一个 blog 在 2D 游戏中创建闪电效果。我想在 python 中实现相同的效果。但是我被困在一个地方。
假设 startpoint 和 endPoint 是二维平面中的坐标,代表线段的极值点。
让我们看看博客中的以下代码片段:
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 中是否有任何内置的 Normalise 和 Perpendicular 函数可以帮助我在 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/