2013-06-03 1 views
2

2D 게임에서 번개 효과 만들기에서 blog을 거쳤습니다. 파이썬에서도 동일한 효과를 구현하고자했습니다. 그러나 나는 한 곳에서 붙어있다.파이썬에서 표준화 및 수직 함수

시작점과 끝점 선분의 극점을 나타내는 2 차원 평면에서의 좌표이다라고하자.

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): 

즉, 라인 (즉, 직각 그 직교하는 벡터를 얻는다


Perpendicular(Normalize(endPoint-startPoint)) 

startPoint를으로부터 엔드 포인트 (길이가 1 인 벡터) 단위 벡터를 얻는다 라인)


나는 정기적 인 p가 아니다. ython 코더. 내장이 있습니까 을 표준으로합니다. 위의 코드를 Python으로 구현하는 데 도움이되는 Python의 함수입니다.

내가 내장 또는 타사 방법을 알고하지 않습니다,하지만 그들은 정말 간단

답변

6

:

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의 1 차원 배열

또는 유사한 유형.

벡터 a의 길이가 0 인 경우 normalize은 예외를 발생시킵니다.

PEP 8, Python 스타일 가이드에 따라 소문자로 이름을 정했습니다.

+0

어떻게'normalize' 메서드를 호출할까요? 내 말은, 'a'라는 주장은 무엇인가? 호출 문을 추가 할 수 있습니까? 시작점 - (x1, y1) : x1 = p, y1 = q라고합시다. 끝점 (x2, y2) : x2 = r 및 y2 = s, 여기서 p, q, r, s는 변수입니다. 고마워요 :) –

+0

나는 희망을 반영하기 위해 나의 예를 확장했다. –

4

numpy 패키지를 살펴 보는 것이 좋습니다. 그것에는 많은 내장 고속 연산이 있습니다. NormalizePerpendicular의 시작 지점으로 normcross을 각각 사용할 수 있습니다.

5

@SethMMorton과 @ThoestenKranz가 지적했듯이 numpy는 벡터 조작에 대한 많은 지원을합니다. 나는 당신이 원하는 것을 얻기 위해 파이썬에 내장 된 지원이 있다고 생각하지 않는다. 그러나 간단한 삼각 함수를 사용하면 내장 수학 모듈을 사용하여 정규화 및 수직 계산을 매우 쉽게 계산할 수 있습니다.

import math 
class Coord(object): 
    def __init__(self,x,y): 
     self.x = x 
     self.y = y 

    def __sub__(self,other): 
     # This allows you to substract vectors 
     return Coord(self.x-other.x,self.y-other.y) 

    def __repr__(self): 
     # Used to get human readable coordinates when printing 
     return "Coord(%f,%f)"%(self.x,self.y) 

    def length(self): 
     # Returns the length of the vector 
     return math.sqrt(self.x**2 + self.y**2) 

    def angle(self): 
     # Returns the vector's angle 
     return math.atan2(self.y,self.x) 

def normalize(coord): 
    return Coord(
     coord.x/coord.length(), 
     coord.y/coord.length() 
     ) 

def perpendicular(coord): 
    # Shifts the angle by pi/2 and calculate the coordinates 
    # using the original vector length 
    return Coord(
     coord.length()*math.cos(coord.angle()+math.pi/2), 
     coord.length()*math.sin(coord.angle()+math.pi/2) 
     ) 

a = Coord(2,12) 
b = Coord(7,5) 
print perpendicular(normalize(a-b)) 
+0

멋지고 우아한 솔루션! – TheInvisibleFist