更改边缘以匹配角度

时间:2016-08-03 21:48:10

标签: python math rotation

我在python中编写脚本并且我对此非常陌生,而且对矢量数学没有太多经验,我可以获得两个向量的点积,长度和角度,我已经设法获得两个点(边缘)之间的差异角度,但我不确定实际修改第二组点以匹配角度的数学/过程第一。我试图做的是旋转第二组点以匹配第一组,无论其当前位置如何。例如:

#python
import math
def dot (v1, v2):
    return (v1[0]*v2[0] + v1[1]*v2[1])
def length (v):
    return math.sqrt(dot(v,v))
def normalize (v):
    r = [0.0] * 2
    v_len = length (v)
    if v_len > 0.0:
            v_invLen = 1.0 / v_len
            r[0] = v[0] * v_invLen
            r[1] = v[1] * v_invLen                
    return r
def direction (v1, v2):
    return (v2[0]-v1[0], v2[1]-v1[1])
def angle(dotProduct):
    return math.degrees(math.acos(dotProduct))

p1,p2 = (0,0),(0,1) <--- first edge
p3,p4 = (0,0),(2,2) <--- second edge
dir = direction(p1,p2)
dir2 = direction(p3,p4)
dir_n = normalize(dir)
dir2_n = normalize(dir2)
dotProduct = dot(dir_n, dir2_n)
ang1 = math.degrees(math.acos(dotProduct))
print ang1  

这给了我一个45度的角度,我试图做的是现在旋转第二个边缘p2以匹配p1的角度,无论它在世界空间中的位置如此p1可能是(1,1), (-2,-2)和p2可能是(-1,1),( - 3,3)需要90度旋转

1 个答案:

答案 0 :(得分:0)

定义一个名为rotate的新函数:

def rotate(v,ang):
    result =[v[0]*math.cos(ang)-v[1]*math.sin(ang),v[0]*math.sin(ang)+v[1]*math.cos(ang)]
    return result

# So to rotate a given vector,lets take your example
p1,p2 = (1,1),(-2,-2)
p3,p4 = (-1,1),(-3,3)

p1,p2 = (1,1),(-2,-2)
p3,p4 = (-1,1),(-3,3)

dir = direction(p1,p2)
dir2 = direction(p3,p4)

dir_n = normalize(dir)
print ("Direction1")
print (dir_n)
dir2_n = normalize(dir2)
print ("Direction2")
print (dir2_n)
dotProduct = dot(dir_n, dir2_n)
ang1 = math.degrees(math.acos(dotProduct))

#Rotate dir2_n in direction of dir_n
new_vec = rotate(dir2_n,math.radians(ang1))
print ("rotated_vector")
print (new_vec)

Output:
Direction1
[-0.7071067811865476, -0.7071067811865476]
Direction2
[-0.7071067811865475, 0.7071067811865475]
rotated_vector
[-0.7071067811865475, -0.7071067811865475]

旋转矢量应与dir_1相同。如果这可以解决您的问题,请告诉我