计算二维类注视函数

2024-06-28 22:14:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用Python创建一个二维的lookAt函数,下面是我的代码

from math import *

def lookAt(segment, originPoint):
    segmentCenterPoint = getSegmentCenter(segment)
    for i in range(2):
        vtx = getVertex(segment, i)
        x, y = getVertexCoord(vtx)
        # Calculate the rotation angle already applied on the polygon
        offsetAngle = atan2(y - segmentCenterPoint.y, x - segmentCenterPoint.x)
        # Calculate the rotation angle to orient the polygon to an origin point
        orientAngle = atan2(segmentCenterPoint.y - originPoint.y, segmentCenterPoint.x - originPoint.x)
        # Get the final angle
        finalAngle = orientAngle - (pi / 2)
        if offsetAngle >= pi:
            offsetAngle -= pi
        elif offsetAngle < 0:
            offsetAngle += pi
        finalAngle += offsetAngle
        # Temporary move the point to have its rotation pivot to (0,0)
        tempX = x - segmentCenterPoint.x
        tempY = y - segmentCenterPoint.y
        # Calculate coords of the point with the rotation applied
        s = sin(finalAngle)
        c = cos(finalAngle)
        newX = tempX * c - tempY * s
        newY = tempX * s + tempY * c
        # Move the point to the initial pivot
        x = newX + segmentCenterPoint.x
        y = newY + segmentCenterPoint.y
        # Apply new coords to the vertex
        setVertexCoord(vtx, x, y)

我手动尝试了一些示例,效果很好,但当我尝试在数千个段上应用该函数时,似乎有些段的方向性不好

我可能错过了什么,但我不知道是什么。还有,也许有更快的方法来计算

谢谢你的帮助

编辑

这是一个可视化的方法,可以更好地理解观察的目的。 我们的目标是找到A和B的坐标,假设我们已经知道O,A和B的坐标([AB]是我们需要垂直于点O的线段)

visualization of lookAt


Tags: thetopisegmentpointcalculateanglerotation
1条回答
网友
1楼 · 发布于 2024-06-28 22:14:42

为了找到A'和B'的位置,你不需要旋转点(并且处理角度)

 Find vector OC = segmentCenterPoint - originPoint
 Make normalized (unit) vector oc = OC / Length(OC)
 Make perpendicular vector  P = (-oc.Y, oc.X)
 Find CB length lCB
 Find A' = C + lCB * P
      B' = C - lCB * P

相关问题 更多 >