【问题标题】:Changing Edges to match angles更改边缘以匹配角度
【发布时间】:2016-12-09 19:12:26
【问题描述】:

我在 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 度

【问题讨论】:

    标签: python math rotation


    【解决方案1】:

    定义一个名为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 相同。让我知道这是否能解决您的问题

    【讨论】:

    • 结果中似乎存在语法错误,可能是 v 之前缺少逗号?我认为 v 需要是 v1
    • 缺少一个减号,已更正。尝试新程序
    • 它似乎工作.. 但后续问题,我可以用旋转矢量做什么?第二条边 (-1,1),(-3,3) 应旋转 90 度以匹配第一条边 (1,1),(-2,-2),其新值应为 (-1,3) ,(-3,1)
    猜你喜欢
    • 2012-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-13
    • 2017-04-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多