python中的规范化和垂直函数 [英] Normalise and Perpendicular Function in python

查看:37
本文介绍了python中的规范化和垂直函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在浏览一个博客 关于在 2D 游戏中创建闪电效果.我想在 python 中实现相同的效果.但是我被困在一个地方.

I was going through a blog on Creating Lightning effect in 2D game.I wanted to implement the same in python. However I am stuck at a place.

假设 startpointendPoint 是 2D 平面中的坐标,代表线段的极值点.

Lets say startpoint and endPoint are co-ordinates in 2D plane , representing extreme points of a line segment.

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

Lets look at following Code Snippet from the blog:

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 的向量)

That line gets a unit vector (vector of length 1) from startPoint to endPoint

Perpendicular(Normalize(endPoint-startPoint))

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

then gets a vector perpendicular to that (i.e. at right angles to the line)

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

I am not a regular python coder. Is there any in-built Normalise and Perpendicular Function in python that would help me in implementing the above code in python.

推荐答案

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

I don't know of built-in or third-party methods, but they are really simple:

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 的一维数组

或类似类型.

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

Be aware that normalize will raise an Exception if the vector a has length zero.

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

I decided to name my functions lower-case according to PEP 8, Python style guide.

这篇关于python中的规范化和垂直函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆