【问题标题】:How to create a triangle with the center coordinates and the coordinates of one point?如何创建一个中心坐标和一个点坐标的三角形?
【发布时间】:2020-07-04 20:54:55
【问题描述】:

我写了一些代码来尝试实现一个函数,它使用屏幕中心的坐标创建一个三角形,在这种情况下它也对应于三角形的中心,这个坐标被标识为“cx”和“ cy”,因为窗口是 800 x 600 cx = 400 和 cy = 300。 有了这个,我创建了一个“第一个点”,它具有相同的中心 x 坐标,但它在中心上方 100 个像素,现在使用中心和第一个点,我试图计算另一个点应该在哪里。 这是代码:

def triangle(cx,cy):
    angle = 2*math.pi/3
    first_point_x = cx
    first_point_y = cy + 100
    vertex = [first_point_x,first_point_y]
    for i in range(2):
        newx = (vertex[i*2]-cx)   * math.cos(angle) - (vertex[i*2+1]-cy) * math.sin(angle)
        newy = (vertex[i*2+1]-cy) * math.cos(angle) + (vertex[i*2]-cx) * math.sin(angle)
        vertex.append(newx)
        vertex.append(newy)
    return vertex

但由于某种原因,该数组给出的负值和数字总体上不符合我想要的。 任何帮助都将不胜感激。

【问题讨论】:

    标签: python geometry pyglet


    【解决方案1】:

    您实际上要做的是计算从 (cx, cy) 到数组中最后一个点的向量,并将向量旋转 120°。但是在将点附加到列表之前,您错过了将向量添加到 (cx, cy) :

    newx = (vertex[i*2]-cx) * math.cos(angle) - (vertex[i*2+1]-cy) * math.sin(angle)
    newy = (vertex[i*2+1]-cy) * math.cos(angle) + (vertex[i*2]-cx) * math.sin(angle)

    newx = cx + (vertex[i*2]-cx)   * math.cos(angle) - (vertex[i*2+1]-cy) * math.sin(angle)
    newy = cy + (vertex[i*2+1]-cy) * math.cos(angle) + (vertex[i*2]-cx) * math.sin(angle)
    

    计算从中心到最后一点的向量

    vx = vertex[i*2] - cx
    vy = vertex[i*2+1] - cy
    

    旋转矢量

    rotated_vx = vx * math.cos(angle) - vy * math.sin(angle)
    rotated_vy = vy * math.cos(angle) + vx * math.sin(angle)
    

    计算新点

    newx = cx + rotated_vx 
    newy = cy + rotated_vy 
    

    【讨论】:

    • 谢谢!它完美无缺!但仍然困扰我的一件事是,如果我创建的向量来自三角形的中心,为什么我需要添加 cx 和 cy?
    • @RuiCoito 向量只是一个方向(和一个距离)。向量没有位置。一个点有一个位置。一个点和一个向量的和就是一个新点。
    • 再次感谢!现在我真的觉得很愚蠢。
    猜你喜欢
    • 1970-01-01
    • 2013-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-16
    相关资源
    最近更新 更多