mickaelb91 mickaelb91 - 1 month ago 16
Python Question

Calculate LookAt like function in 2 dimensions

I'm trying to create a lookAt function in 2 dimensions using Python, so here's my code right now.

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)


I tried some examples manually and worked well, but when I tried to apply the function on thousands of segments, it seems some segment are not well oriented.

I probably missed something but i don't know what it is. Also, maybe there's a faster way to calculate it ?

Thank you for your help.

EDIT

Here is a visualization to understand better the goal of the lookAt.
The goal is to find A' and B' coordinates, assuming we already know O, A and B ones. ([AB] is the segment we need to orient perpendicularly to the point O)

visualization of lookAt

MBo MBo
Answer

To find positions of A' and B', you don't need rotate points (and dealt with angles at all).

 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